【问题标题】:C++ Detect input redirection [duplicate]C ++检测输入重定向[重复]
【发布时间】:2011-12-26 02:53:37
【问题描述】:

可能重复:
Detect if stdin is a terminal or pipe in C/C++/Qt?

假设我们有一个小程序,它接受一些标准 C 输入。

我想知道用户是否正在使用输入重定向,例如这样:

./programm < in.txt

有没有办法检测这种输入重定向的方式程序中?

【问题讨论】:

标签: c++ iostream io-redirection


【解决方案1】:

没有可移植的方法来做到这一点,因为 C++ 没有说明cin 的来源。在 Posix 系统上,您可以测试 cin 是来自终端还是使用 isatty 重定向,如下所示:

#include <unistd.h>

if (isatty(STDIN_FILENO)) {
    // not redirected
} else {
    // redirected
}

【讨论】:

    【解决方案2】:

    在 posix 系统上,您可以使用isatty function。标准输入为file descriptor0。

    isatty(0); // if this is true then you haven't redirected the input
    

    【讨论】:

    • 你可以说0而不是fileno(std::stdin),不过:-)
    • @KerrekSB:或者STDIN_FILENO,如果你不想调用不必要的函数的话。
    【解决方案3】:

    在标准 C++ 中,您不能。但是在 Posix 系统上,您可以使用 isatty:

    #include <unistd.h>
    #include <iostream>
    
    int const fd_stdin = 0;
    int const fd_stdout = 1;
    int const fd_stderr = 2;
    
    int main()
    {
      if (isatty(fd_stdin)) 
        std::cout << "Standard input was not redirected\n";
      else
        std::cout << "Standard input was redirected\n";
      return 0;
    }
    

    【讨论】:

      【解决方案4】:

      在 POSIX 系统上,您可以测试标准输入,即 fd 0 是否是 TTY:

      #include <unistd.h>
      
      is_redirected() {
          return !isatty(0) || !isatty(1) || !isatty(2);
      }
      
      is_input_redirected() {
          return !isatty(0);
      }
      
      is_output_redirected() {
          return !isatty(1) || !isatty(2);
      }
      
      is_stdout_redirected() {
          return !isatty(1);
      }
      
      is_stderr_redirected() {
          return !isatty(2);
      }
      

      这不是 C++ 标准库的一部分,但如果在可用生态系统的 POSIX 系统上运行,您的程序将会存在。请随意使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-24
        • 2011-02-02
        • 1970-01-01
        • 2017-09-22
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多