File Handling in C

File handling in C allows programs to read and write data to files, making it possible to store and retrieve information for later use. This tutorial covers the basics of opening, reading, writing, and closing files in C.

Step 1: Understanding File Handling in C

C uses the FILE structure from stdio.h for file operations. The basic file functions include:

  • fopen() – Opens a file.
  • fclose() – Closes a file.
  • fprintf() – Writes formatted data to a file.
  • fscanf() – Reads formatted data from a file.
  • fgets() – Reads a line from a file.
  • fputs() – Writes a line to a file.

Step 2: Opening a File

The fopen() function is used to open a file:

FILE *filePointer;
    filePointer = fopen("example.txt", "w");

File modes:

  • "r" – Read mode (file must exist).
  • "w" – Write mode (creates or overwrites a file).
  • "a" – Append mode (adds data to an existing file).
  • "r+", "w+", "a+" – Read and write modes.

Step 3: Writing to a File

Use fprintf() to write formatted text:

#include <stdio.h>

    int main() {
        FILE *file = fopen("example.txt", "w");

        if (file == NULL) {
            printf("Error opening file!\n");
            return 1;
        }

        fprintf(file, "Hello, World!\n");
        fclose(file);
        return 0;
    }

Step 4: Reading from a File

Use fscanf() to read formatted input:

#include <stdio.h>

    int main() {
        FILE *file = fopen("example.txt", "r");
        char text[100];

        if (file == NULL) {
            printf("Error opening file!\n");
            return 1;
        }

        fscanf(file, "%s", text);
        printf("File content: %s\n", text);

        fclose(file);
        return 0;
    }

Step 5: Reading a File Line by Line

Use fgets() for line-by-line reading:

#include <stdio.h>

    int main() {
        FILE *file = fopen("example.txt", "r");
        char line[256];

        if (file == NULL) {
            printf("Error opening file!\n");
            return 1;
        }

        while (fgets(line, sizeof(line), file)) {
            printf("%s", line);
        }

        fclose(file);
        return 0;
    }

Step 6: Appending Data to a File

Use "a" mode to append text:

FILE *file = fopen("example.txt", "a");
    fprintf(file, "Appending text\n");
    fclose(file);

Step 7: Closing a File

Always close a file after use with fclose():

fclose(file);

Step 8: Error Handling

Check if a file was opened successfully:

if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

Next Steps

Practice file handling by:

  • Creating a program to store and retrieve user data.
  • Using file operations in a real-world project.

For more advanced file operations, explore binary file handling with fwrite() and fread().