C ++ Detecting Input

Possible duplicate:
Determine if stdin is a terminal or a pipe in C / C ++ / Qt?

We assume we have got a little program that takes some C standard input.

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

./programm < in.txt

      

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

+2


source to share


4 answers


There is no portable way to do this as C ++ says nothing about where it comes from cin

. On Posix system, you can check whether or not comes cin

from terminal or redirects with isatty

, something like this:



#include <unistd.h>

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

      

+8


source


On posix system, you can use isatty function . Standard input file descriptor 0.



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

      

+4


source


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

      

+2


source


On POSIX system, you can check if stdin is, i.e. fd 0 is 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 you are running on a POSIX system then your program will live. Feel free to use it.

+1


source







All Articles