-1

Linux manual recommends that the fflush function should not be used.

So, I found that while( getchar() != '\n' plays the same role as fflush(stdin).

e.g.)

my trial code:

#include <stdio.h>

void main(void)
{
    char input[100] = {};
    printf("abcd");
    while(1);
}

If I execute the code above in Linux (Ubuntu), the result is nothing. Because \n is not in string. So, I have to print them out by emptying stdout buffer.

The strange phenomenon is that the result is printed well when I use either getc(stdout) or getc(stdin).

#include <stdio.h>

void main(void)
{
    char input[100] = {};
    printf("abcd");
    getc(stdout); // or getc(stdin); both working well.
    while(1);
}

I don't know why both are done well. I expected that only getc(stdout) should work well because I regard stdin as keyboard buffer and stdout as monitor buffer.

Graham Charles
  • 9,394
  • 3
  • 26
  • 41
Danny_Kim
  • 299
  • 2
  • 18

2 Answers2

2

Read carefully the documentation of fflush(3) (for input streams, it has a documented effect only on seekable files, not on stdin when it is a terminal). AFAIK, fflush(stdin) is undefined behavior (when stdin is a terminal), and certainly does not do the same as while( getchar() != '\n'; you should call fflush on some output FILE* handle or on NULL

Your first example would work as expected if you add a fflush(NULL); or a fflush(stdout); call before the while(1); busy waiting loop (actually, you should call sleep(3) inside that loop, at least to avoid heating your processor).

Notice that stdin can (on Linux) be a tty(4), or a file or a pipe(7) (e.g. with shell redirection or pipelines), etc....

Terminals, that is ttys, are -mostly for historical reasons- quite complex things. Read the tty demystified page. In many situations, you have some double buffering: the kernel is buffering the tty thru its line discipline, and the C standard library is buffering the stdin. See setvbuf(3). Of course a tty is not the keyboard (but some abstraction above it). Very likely, on your Linux desktop, the physical keyboard is only read by the X11 server.

If you care about interactive input from a terminal, consider using some library like ncurses or readline

Read Advanced Linux Programming

And the behavior of your second case can be explained by the fact that some C standard libraries are implicitly flushing stdout before reading from stdin, but AFAIK this is not guaranteed, and you certainly should call explicitly fflush (in particular, for readability reasons) when needed!

Read the documentation of getc(3), it can fail (and probably would fail with stdout).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
-1

You can use setbuf(stdout, NULL); function call to get same effect as fflush(stdin).

anshul garg
  • 473
  • 3
  • 7