Introduction
File handling in C allows programmers to store data permanently in files and retrieve it whenever needed. C provides various functions to create, read, write, and modify files.
Key Functions for File Handling
fopen()
: Opens a file.fprintf()
: Writes formatted data to a file.fscanf()
: Reads formatted data from a file.fclose()
: Closes a file.fgets()
: Reads a line from a file.fputs()
: Writes a line to a file.fseek()
: Moves the file pointer to a specific location.fflush()
: Flushes the output buffer, forcing data to be written immediately.
Using fflush()
The fflush()
function is used to clear the output buffer by writing its content to the file immediately. It is often used when writing to files to ensure data is saved, especially in programs with intermediate outputs.
Example: Writing to a File with fflush()
#include <stdio.h> int main() { FILE *filePointer = fopen("data.txt", "w"); if (filePointer == NULL) { printf("Error: Could not open file.\n"); return 1; } fprintf(filePointer, "This is a test line.\n"); fflush(filePointer); // Force writing data to the file immediately fprintf(filePointer, "Another line written after flushing.\n"); fclose(filePointer); printf("Data written and flushed successfully.\n"); return 0; }
Output: The file data.txt
will immediately contain the first line, even before the second line is written.
Additional Notes:
fflush(stdout)
: Clears the output buffer of the console (used for printf).- Always close the file with
fclose()
after flushing. fflush(stdin)
is non-standard and may behave unpredictably on some compilers.
Unsolved Problems
- Write a program to count the number of words in a file.
- Write a program to find the size of a given file.
- Write a program to reverse the content of a file.
- Write a program to copy content from one file to another.
- Write a program to merge two files into a new file.
- Write a program to read and display the last N lines of a file.
- Write a program to find the frequency of a specific word in a file.
- Write a program to check if a file exists before opening it.
- Write a program to replace all occurrences of a word in a file.
- Write a program to generate a file containing a multiplication table.