有没有办法来确定stdout是否指向控制台

有没有办法来确定stdout是否指向控制台

本文介绍了有没有办法来确定stdout是否指向控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将代码插入到运行在Windows上的C ++应用程序中,该应用程序可以确定stdout(或cout)是否指向控制台,如果是,则在将其写入终端编码之前将其转换为终端编码。如果没有(例如,如果写入文件或管道),则应该保留字符。转换部分不是一个问题,但我想知道是否甚至可能的应用程序知道它的stdout是到控制台或其他地方。

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.

我不确定Windows API函数GetStdHandle是否有任何帮助,或者它是否仅仅是一种指向stdout而不能确定任何信息的方法关于它。同样,我不确定是否有任何信息,我们可以从cout获得,这将表明它是指向一个控制台或其他东西。

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 ()您想要了解的句柄。如果它被重定向到另一个控制台句柄以外的东西(例如到文件),那么 GetConsoleMode 将失败。例如:

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;

这篇关于有没有办法来确定stdout是否指向控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:58