whats the use of fflush function in c. when to use it and what does it do. what happens if you dont use it

fflush function is something that i came across in a chapter on structures in c

@imcode Here you will find everything on fflush function including its implementation.

Hope it help :slight_smile:

In ANSI, fflush() [returns 0 if buffer successfully deleted / returns EOF on an error] causes the system to empty the buffer associated with the specified output stream.
It undoes the effect of any ungetc() function if the stream is open for input. The stream remains open after the call.
If stream is NULL, the system flushes all open streams.

However, the system automatically deletes buffers when the stream is closed or even when a program ends normally without closing the stream.

It clears the output buffer, so this not interfere wrong on the next operation. And in Input operations, it will write the data on the destiny and erase the buffer.

A fast example, if you use a scanf operation, then a fgets, the fgets will only read the \n. If you use the fflush after the scanf, the fgets will work normally.

3 Likes

fflush is the function which delete and free the buffer that the next output cannot interfere with the previous one…

fflush is the function which delete and free the buffer that the next output cannot interfere with the previous one…

If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.

If stream is a null pointer, all such streams are flushed.

In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).

The stream remains open after this call.

When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.

Refer here for more :
http://www.cplusplus.com/reference/cstdio/fflush/

//