我想将代码插入到运行在Windows上的C ++应用程序中,该应用程序可以确定stdout(或cout)是否指向控制台,如果是,则在将字符写入之前将字符转换为终端编码。 如果不是(例如,如果写入文件或管道),则应保留字符。 转换部分不是问题,但我想知道应用程序是否有可能知道它的stdout是否会进入控制台或其他地方。
我不确定Windows API函数GetStdHandle是否会有任何帮助,或者它是否只是一种指向stdout的方法,而无法确定任何有关它的信息。 同样,我不确定是否有任何我们可以从cout获得的信息,表明它是指向控制台还是其他东西。 到目前为止,我还没有找到这些方面的任何内容。
I would like to insert code into a C++ application running on Windows that can determine whether stdout (or cout) is pointing to the console, and if it is, convert characters to terminal encoding before writing them out. If not (for instance, if writing to a file or pipe), the characters should be left alone. The conversion part is not a problem, but I'm wondering whether it's even possible for an application to know whether its stdout is going to the console or elsewhere.
I am not sure whether the Windows API function GetStdHandle would be of any help, or whether it simply is a means of pointing to the stdout without being able to determine any information about it. Likewise, I'm not sure whether there's any information that we can obtain from cout that would indicate whether it's pointing to a console or something else. So far, I haven't been able to find anything along those lines.
最满意答案
在您想要了解的句柄上调用GetConsoleMode ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167 ( GetConsoleMode ) .aspx )。 如果将其重定向到另一个控制台句柄以外的其他GetConsoleMode (例如,文件),则GetConsoleMode将失败。 例如:
DWORD temp; const BOOL success = GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &temp); const bool redirected = success == FALSE;Call GetConsoleMode (http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx) on the handle you want to know about. If it's redirected to something other than another console handle (e.g. to a file) then GetConsoleMode will fail. For example:
DWORD temp; const BOOL success = GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &temp); const bool redirected = success == FALSE;更多推荐
发布评论