2

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?

Community
  • 1
  • 1
Tieme
  • 62,602
  • 20
  • 102
  • 156
  • 1
    Maybe this will help: http://stackoverflow.com/questions/2216529/check-for-unix-command-line-arguments-pipes-and-redirects-from-a-c-program – darnir Nov 10 '11 at 12:03
  • 1
    Related: http://stackoverflow.com/questions/2027484/determine-whether-process-output-is-being-redirected-in-c-c – IronMensan Nov 10 '11 at 12:06
  • Why do you need to know. The whole point is to make the input look the same. – Martin York Nov 10 '11 at 14:15
  • 4
    @LokiAstari: You might want to prompt the user for input when reading from a terminal, and not otherwise. – Mike Seymour Nov 10 '11 at 15:07

4 Answers4

8

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
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
4

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
INS
  • 10,594
  • 7
  • 58
  • 89
2

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;
}
celtschk
  • 19,311
  • 3
  • 39
  • 64
1

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.

datenwolf
  • 159,371
  • 13
  • 185
  • 298