2

可能重复:
检测标准输入是否是 C/C++/Qt 中的终端或管道?

考虑我们有一个小程序,它需要一些标准的 C 输入。

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

./programm < in.txt

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

4

4 回答 4

8

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

#include <unistd.h>

if (isatty(STDIN_FILENO)) {
    // not redirected
} else {
    // redirected
}
于 2011-11-10T12:04:52.670 回答
4

在 posix 系统上,您可以使用isatty 函数。标准输入是文件描述符0。

isatty(0); // if this is true then you haven't redirected the input
于 2011-11-10T12:02:55.220 回答
2

在标准 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;
}
于 2011-11-10T12:03:41.770 回答
1

在 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 系统部分上运行,您的程序将会存在。随意使用它。

于 2011-11-10T12:11:22.333 回答