c++ - 如何判断 stderr 是否已在 Windows 中重定向?

标签 c++ c windows winapi console

我希望我的程序在 stderr 连接到控制台时和重定向到文件/管道时具有不同的行为。在 Unix 系统中,我可以只测试 isatty(STDERR_FILENO),但我如何在 Windows 中执行此操作? MSVCRT 也有一个名为 _isatty 的函数,它不能正常运行(例如 Detect NUL file descriptor (isatty is bogus) )。我可以调用任何 Windows 或 NT API 来测试它吗?

最佳答案

  1. 调用 GetStdHandle 获取标准错误句柄。
  2. 将该句柄传递给 GetFileType 以找出它是什么类型的文件。
  3. 如果返回 FILE_TYPE_CHAR,则 stderr 可能是一个控制台,但调用 GetConsoleMode 进行检查。
  4. 如果 GetConsoleMode 失败,则 stderr 已被重定向到另一个字符设备,例如打印机。

关于c++ - 如何判断 stderr 是否已在 Windows 中重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42139699/

相关文章:

c++ - 在带有 std::unordered_map 的 std::scoped_allocator_adaptor 中使用自定义分配器

将代码从 'hard-coding' 转换为 'soft-coding'

windows - 从网络共享 "This page has an unspecified potential security flaw."复制时出错

eclipse - 如何解决 SVN 错误 "E200030: There are unfinished transactions detected in ' <CHECKOUT_DIRECTORY >'"?

c++ - 在哪里放置效用函数

c++ - 从文件夹创建 zip 文件 - 在 C++ 中

java - C++ Thrift : Can I use TFramedTransportFactory with TThreadedServer?

objective-c - Objective C bool 属性和内存

c - 为什么我的 printf() 不打印文本文件中的第一个字符?

windows - GotoMeeting 等软件如何捕获桌面图像?