Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Determine if STDIN is Empty?

Tags:

c++

iostream

I'm writing an emulator for my Operating Systems course. The problem I have is that we need to get all our .job files (they are like application programs being fed to the emulator) from STDIN and read them in.

Call:

./RMMIX < aJob.job

I just slurp it with

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

line by line. The problem is, if I do not put anything to STDIN, then cin will wait for user input- NOT what I want. I need the program to recognize a lack of text on STDIN and terminate, not wait for user input instead.

I have determined that I can query the length like so:

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 has a length of 0.

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

like image 753
IAE Avatar asked May 04 '11 09:05

IAE


People also ask

How do you know when stdin ends?

The simple, non-technical, answer is that Ctrl + D terminates the STDIN file and that Ctrl + C terminates the active application.

How do I stop stdin from reading?

You can close STDIN by pressing Ctrl-d on Unix-like systems or Ctrl-z on Windows.

What happens if you close stdin?

close(fileno(stdin)) causes any further attempts at input from stdin , after the current buffer has been depleted, to fail with EBADF , but only until you open another file, in which case that file will become fd #0 and bad things will happen.

Is stdin a buffer?

stdin is buffered (line buffering doesn't affect stdin) stdout is buffered (line buffered if connected to a terminal) stderr is unbuffered.


1 Answers

I don't think there's a platform independent way of doing this, but on Unix-based systems you should be able to do:

#include <unistd.h>
...

int main() {
    if (!isatty(0)) {
        // stdin is being streamed from a file or something else that's not a TTY.
    }

    ...
}

However, I think doing it via a command line option is the preferred approach.

like image 90
hammar Avatar answered Sep 28 '22 03:09

hammar