C fflush() Function

beginner
25 min

C fflush() Function

Welcome to our deep dive into the fflush() function in C programming! 🎯

This function is a powerful tool for handling stream output. Let's start by understanding what a stream is. In C, a stream is an abstract data type that represents an input or output source or destination. 📝

The fflush() Function Explained 💡

The fflush() function is used to flush (empty) the output buffer for a given stream. It ensures that all the data written to the stream is actually sent to the output device (like the console or a file).

Syntax

c
int fflush(FILE *stream);

The fflush() function takes one argument, stream, which is a pointer to a FILE structure. This structure contains information about the stream, such as its file pointer, file name, and mode.

Usage

Let's see a simple example to understand better.

c
#include <stdio.h> int main() { FILE *file; char str[] = "Hello, World!"; file = fopen("output.txt", "w"); fprintf(file, "%s", str); fclose(file); // Flush the output buffer of the file fflush(file); // Open the file for reading file = fopen("output.txt", "r"); char c; while ((c = fgetc(file)) != EOF) { printf("%c", c); } fclose(file); return 0; }

In this example, we open a file called output.txt for writing, write a string to it, and then close the file. We then reopen the file for reading and print its contents to the console. After writing the data to the file, we call fflush(file) to ensure that all data has been written to the file before we try to read it.

Pro Tip 💡

Remember, fflush() only flushes the output buffer for the specified stream. If you want to flush all output buffers, you can call fflush(NULL).

Quiz

Quick Quiz
Question 1 of 1

What does the `fflush()` function do in C programming?

Happy coding! 🎉