How to check if stdin is in C

I am (re) learning C programming, so the following question is needed for understanding. Using scanf (), I found out (or found out myself that it really won’t take long) that flushing stdin is good. I also found out (with your help) that fflush (stdin) is not a standard thing and, for example, does not work with gcc. I switched to using the code snippet below to clear stdin. It was provided here (thanks). It works fine if stdin is not empty. However, if stdin is empty, it does not work. The fgetc () function in my cleanup function just waits and blocks the program. And in fact, all the other stdin reading functions that I still know (scanf (), fgetc (), gets (), fgets (), getchar ()) show the same behavior. So my flushing function is actually a conditional cleanup: it only gets reset,if the buffer is not empty. If it is empty, then flushing blocks the program and waits for input to stdin. This is not what I want. So, I need a way to check if stdin is empty. If I continue. If this is not my flushing function.

So, what I'm looking for is the standard C way to check if stdin is empty.

Thanks for the help!

void flush_line(FILE *);


/* function to flush stdin in a C standard way since*/
/* fflush(stdin) has undefined behaviour. */
/* s. http://stackoverflow.com/questions/20081062/fflushstdin-does-not-work-compiled-with-gcc-in-cygwin-but-does-compiled-with-v */
void flush_line(FILE *fin)
{
    int ch;
    do
    {
        ch = fgetc(fin);

    } while (ch != '\n' && ch != EOF);

}
+4
source share
3 answers

You can use select or poll to check if the file descriptor is read. But not in ANSI C.

0
source

I decided that in cancer , but it works fine. If it works only if stdin is dirty (not empty), so just send \nto stdin always before clearing it. Yes, I know, it seems like a very ugly solution, but this is the only reasonable way that I can consider it portable, since selection or polling does not work with Windows).

Here:

void flush_stdin() {
    char c;
    ungetc('\n', stdin); // ensure that stdin is always dirty
    while(((c = getchar()) != '\n') && (c != EOF));
}
0
source

stdin , . - : , .

, "" (, "" ) . , , . , "", ! .

, ( - ?), , . "" ; , - , , , .

0

All Articles