fflush() is not working in Linux

Don't use fflush, use this function instead:

#include <stdio.h>
void clean_stdin(void)
{
    int c;
    do {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

fflush(stdin) depends of the implementation, but this function always works. In C, it is considered bad practice to use fflush(stdin).


The behavior of fflush is not defined for input streams (online 2011 standard):

7.21.5.2 The fflush function

Synopsis

1

    #include <stdio.h>
    int fflush(FILE *stream);
Description

2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

3 If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above.

Returns

4 The fflush function sets the error indicator for the stream and returns EOF if a write error occurs, otherwise it returns zero.

I faced the same problem while working on LINUX and an alternative solution of this problem can be that you define a dummy character lets say char dummy; and put a scanf() to scan it just before your actual input takes place. This worked for me. I hope it would work for you too.


One that always works on Linux:

#include <termios.h>
#include <unistd.h>

void clean_stdin()
{
        int stdin_copy = dup(STDIN_FILENO);
        /* remove garbage from stdin */
        tcdrain(stdin_copy);
        tcflush(stdin_copy, TCIFLUSH);
        close(stdin_copy);
}

You can use tcdrain and tcflush not only for in/out/err fd.

Tags:

Linux

C

Gcc