C++ Detect input redirection [duplicate]

瘦欲@ 提交于 2019-12-01 11:29:18

There's no portable way to do that, since C++ says nothing about where cin comes from. On a Posix system, you can test whether or not cin comes from a terminal or is redirected using isatty, something like this:

#include <unistd.h>

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

On a posix system you can use the isatty function. The standard input is file descriptor 0.

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

In standard C++, you can't. However on Posix systems you can using 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;
}

On a POSIX system you can test if stdin, i.e. fd 0 is a 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);
}

This is not part of the C++ standard library, but if running on a POSIX system part of the evailable ecosystem your program is going to live in. Feel free to use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!