C++检测输入重定向

C++ Detect input redirection

本文关键字:重定向 输入 检测 C++      更新时间:2023-10-16

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

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

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

./programm < in.txt

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

没有可移植的方法,因为C++没有说明cin来自哪里。在Posix系统上,您可以测试cin是否来自终端或使用isatty重定向,类似于以下内容:

#include <unistd.h>
if (isatty(STDIN_FILENO)) {
    // not redirected
} else {
    // redirected
}

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

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

在标准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 redirectedn";
  else
    std::cout << "Standard input was redirectedn";
  return 0;
}

在POSIX系统上,您可以测试stdin,即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系统上运行,则是程序将要生活的可疏散生态系统的一部分。请随意使用。