C++检测输入重定向
C++ Detect input redirection
可能重复:
检测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系统上运行,则是程序将要生活的可疏散生态系统的一部分。请随意使用。
相关文章:
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- 使用 dup2() 进行输入重定向
- 重定向输入和输出时如何处理主文件I/O?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 当使用带有stdin和stdout重定向的双进程管道时,如何避免stdin上的重复输入
- 将两个独立的stdin重定向为程序的输入
- 分段错误(核心转储) 重定向输入
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 即使可执行文件的输入是从文件重定向的,如何强制从终端输入?
- 输入重定向读取整数和char C
- 将线程之间的标准输入/输出重定向
- C++输入重定向导致文件参数工作时出错
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何在 c++ 中使用输入重定向添加整数
- 在while循环中使用输入重定向
- C++ - 使用 IO 重定向输入和输出多个整数
- 使用重定向输入和输出的c++进程间通信不适用于发布版本
- 当重定向输入流到字符串时,c++程序核心转储
- 使用stdin重定向输入