Reading from STDIN if not empty

I need to make a program in c that reads and parses STDIN. Here's my problem: I'm already managing multiple error cases in STDIN (wrong format, etc.), but if nothing is provided, the program keeps listening to user input. I want it to throw an error like "Nothing to read". Is it possible?

+3


source to share


2 answers


If you are under a UNIX-like operating system, you can use select()

to wait for a given input time and if not just keep going.

This is great for waiting on the inputs for any of a significant number of different file descriptors, but can easily be used for standard input if you want.

Alternatively, you can look at the terminal functions if you are sure that it is coming from the terminal, using tcgetattr()

and tcsetattr()

to put the terminal in non-canonical mode and set a timeout:



#include <termios.h>
struct termios tio;
tcgetattr(fd, &tio);             // Get current
tio.c_lflag &= ~ICANON;          // Non-canonical
tio.c_cc[VTIME] = 50;            // Five second timeout
tcsetattr(fd, TCSANOW, &tio);    // Set new

      

The (ISO) C standard, unfortunately, does not have any that are provided.

+2


source


Your question, as formulated, is meaningless. If the input comes from something that looks like a pipe, there is no way to know how long it will take more input. (and writing to the other end will fail until a reader appears, although often the parent process will still count as a reader, even though it's not actually trying to read).



However, if you want to prevent hangs when the input is interactive, just use isatty(3)

and don't read in that case.

+1


source







All Articles