有没有办法确定stdout是否指向控制台?(Is there a way to determine whether stdout is pointing to the console?)

编程入门 行业动态 更新时间:2024-10-28 00:15:16
有没有办法确定stdout是否指向控制台?(Is there a way to determine whether stdout is pointing to the console?)

我想将代码插入到运行在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;

更多推荐

本文发布于:2023-08-07 21:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   没有办法   stdout   console   determine

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!