How to determine if STDIN is empty?

I am writing an emulator for my course "Operating Systems". The problem is that we need to get all of our .job files (they are similar to the application programs that are served in the emulator) from STDIN and read them.

Call:

./RMMIX < aJob.job 

I just use

 while(getline(std::cin, line)) 

line by line. The problem is that if I don’t use anything for STDIN, then cin will wait for user input - NOT what I want. I need a program to recognize a lack of text in STDIN and stop working, and not wait for user input.

I decided that I could request the length as follows:

 size_t beg = std::cin.tellg(); std::cin.seekg(0, std::ios_base::end); size_t end = std::cin.tellg(); std::cin.seekg(0, std::ios_base::beg); 

and terminate if std :: cin is 0 in length.

Are there any other solutions? Is this a portable solution?

+7
source share
4 answers

I don't think this is a platform-independent way of doing this, but on Unix based systems you can:

 #include <unistd.h> ... int main() { if (!isatty(0)) { // stdin is being streamed from a file or something else that not a TTY. } ... } 

However, I think that doing this using the command line option is preferable.

+4
source

You need to reverse engineer your program. Instead of reading from standard input, read from a named file whose name you specify on the command line. Then instead of:

 ./RMMIX < aJob.job 

you speak:

 ./RMMIX aJob.job 

This is much simpler and more portable than trying to determine if there is anything in the standard input.

+2
source

You can also look at http://www.programmersheaven.com/mb/CandCPP/232821/232821/non-blocking-reads-on-stdin/ for an idea that arises in a problem from another direction - do not check the number of bytes in the stream but instead, just do the reading right away and then check to see if something has been read.

+2
source

You can press Ctrl + D at the command line to signal the end of the file for standard input in the current program.

This is the desired behavior. Otherwise, if programs exited immediately when there was no input, the pipelines could be accidentally broken by commands that were waiting for another command that was not scheduled to run (and which did not produce any additional output), or that the buffered output emitted all this at once how sort does.

When using io redirection to output stdin from a file using something like ./RMMIX < file.txt , this end-of-file condition is signaled automatically when there is no more data in the file. For input read from the terminal, a wait is probably desired.

0
source

All Articles