Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Detect input redirection [duplicate]

Possible Duplicate:
Detect if stdin is a terminal or pipe in C/C++/Qt?

Consider we got a small program which takes some standard C input.

I would like to know if the user is using input redirection, for example like this:

./programm < in.txt

Is there a way to detect this way of input redirecting in the program?

like image 794
Tieme Avatar asked May 01 '26 08:05

Tieme


2 Answers

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
}
like image 148
Mike Seymour Avatar answered May 03 '26 01:05

Mike Seymour


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
like image 44
INS Avatar answered May 03 '26 02:05

INS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!