How to check if my program has data in it

I am writing a program that should read input via stdin, so I have the following construct.

FILE *fp=stdin; 

But it just freezes if the user has not transferred anything to the program, how can I check if the user actually transfers data to my program, for example

 gunzip -c file.gz |./a.out #should work ./a.out #should exit program with nice msg. 

thanks

+7
c ++ c pipe stdin
source share
6 answers

Since you use file pointers, you need both isatty() and fileno() :

 #include <unistd.h> #include <stdio.h> int main(int argc, char* argv[]) { FILE* fp = stdin; if(isatty(fileno(fp))) { fprintf(stderr, "A nice msg.\n"); exit(1); } /* carry on... */ return 0; } 

Actually, this is a long way. In short, file pointers should not be used:

 #include <unistd.h> int main(int argc, char* argv[]) { if(isatty(STDIN_FILENO)) { fprintf(stderr, "A nice msg.\n"); exit(1); } /* carry on... */ return 0; } 

Several standard Unix programs perform this test to change their behavior. For example, if you configured ls to give you beautiful colors, it will turn off colors if you pass it stdout to another program.

+8
source share

Passing stdin to select () or poll () should tell you if the input is waiting. On many operating systems, you can also indicate whether stdin is tty or pipe.

EDIT: I see that I will also need to emphasize part of the tty test. Filo is not tty, but there can be no input ready for an indefinite period of time.

+3
source share

Try "man isatty", I think the function will tell you if you are talking to the user or not.

+3
source share

Use isatty to find that stdin is coming from the terminal, not from a redirect.

+2
source share

See the "isatty" function - if STDIN is a terminal, you can skip reading from it. If it is not a terminal, you receive data via channels or redirected, and you can read before EOF.

+1
source share

An additional parameter that you get with select () sets the timeout for reading from stdin (relative to the first read from stdin or sequential reads from stdin).

For sample code using select on stdin see:

How to check if stdin is open without blocking?

0
source share

All Articles