Assuming you're on some kind of Unix variant....
There are two things you need to clear here:
- The
FILE *
input buffer managed by the C library.
- The OS input buffer that your program has not yet read.
The first can be cleared with fflush
, just like output streams, except that the data is simply discarded rather than written out.
The second requires some low-level OS I/O calls. In general you should not mix these with the FILE *
I/O functions, but they should be safe between fflush
and any other read/get operation.
First, you'll need to use select
to see if a read
operation would block. This effectively checks to see if the OS buffer is clear. If the read
would not block, then you do a one-character read
, and repeat the select. The key point is that you have to check if there is data to read before you read and discard it, or else it will block until there is data to read.
The code might look something like this (untested):
fflush(stdin);
int stdinin_fd = fileno(stdin);
while (1) {
fdset readset;
FD_ZERO(&readset);
FD_SET(stdin_fd, &readset);
struct timeval timeout = {0, 0};
int result = select(stdin_fd+1, &readset, NULL, NULL, timeout);
if (result == 1) {
char c;
read(stdin_fd, &c, 1);
} else if (result == 0
|| (result == -1 && errno != EINTR)) {
break;
} // else loop
}
It might be possible use a larger read-size when clearing the OS buffers, which would be more efficient, but I'm not sure about the portability of that, and anyway I'm assuming there won't be much data to clear.