Understanding File Handling in C

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

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:

Unsolved Problems

  1. Write a program to count the number of words in a file.
  2. Write a program to find the size of a given file.
  3. Write a program to reverse the content of a file.
  4. Write a program to copy content from one file to another.
  5. Write a program to merge two files into a new file.
  6. Write a program to read and display the last N lines of a file.
  7. Write a program to find the frequency of a specific word in a file.
  8. Write a program to check if a file exists before opening it.
  9. Write a program to replace all occurrences of a word in a file.
  10. Write a program to generate a file containing a multiplication table.