C File Handling Introduction

Master file operations in C programming

📁 What is File Handling in C?

File handling in C allows programs to store data permanently by reading from and writing to files on disk storage systems.


#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    fprintf(file, "Hello, File Handling!");
    fclose(file);
    return 0;
}
                                    

Output:

Creates a file named "example.txt" with content: "Hello, File Handling!"

Key File Handling Concepts

📝

Create Files

Create new files using fopen() function

FILE *fp = fopen("data.txt", "w");
✍️

Write Files

Write data to files using fprintf(), fputs()

fprintf(fp, "Hello World!");
📖

Read Files

Read data from files using fscanf(), fgets()

fscanf(fp, "%s", buffer);
🔢

Binary Files

Handle binary data with fread(), fwrite()

fwrite(&data, sizeof(int), 1, fp);

🔹 File Pointer and FILE Structure

In C, the FILE structure represents opened files and the file pointer is the primary way to interact with files. fopen() returns a FILE pointer that acts as a reference to the opened file, enabling all subsequent read and write operations. The FILE structure contains internal buffering information, file position tracking, and error status. Always maintain FILE pointers carefully, pass them correctly between functions, and avoid using pointers after files close to prevent undefined behavior.

#include <stdio.h>

int main() {
    FILE *filePtr;  // Declare file pointer
    
    // Open file for writing
    filePtr = fopen("myfile.txt", "w");
    
    if (filePtr == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    printf("File opened successfully!\n");
    fclose(filePtr);  // Always close the file
    return 0;
}

Output:

File opened successfully!

🔹 File Opening Modes

Understanding different file opening modes is essential for correct file operations in C programming. Mode r opens existing files for reading only, w creates new files for writing or truncates existing ones, and a opens files for appending new data at the end. Additional modifiers like + add read-write capability, and b specifies binary mode for non-text data. Selecting the correct mode ensures you can perform intended operations and prevents unintended data loss or access errors.

// Text file modes
FILE *fp1 = fopen("file.txt", "r");   // Read only
FILE *fp2 = fopen("file.txt", "w");   // Write only
FILE *fp3 = fopen("file.txt", "a");   // Append
FILE *fp4 = fopen("file.txt", "r+");  // Read and write

// Binary file modes
FILE *fp5 = fopen("file.bin", "rb");  // Read binary
FILE *fp6 = fopen("file.bin", "wb");  // Write binary
FILE *fp7 = fopen("file.bin", "ab");  // Append binary

Mode Explanation:

r - Read, w - Write, a - Append

+ - Read and Write, b - Binary mode

🔹 Basic File Operations

Essential file operations in C include writing data with fprintf(), reading data with fscanf(), and managing files with fopen() and fclose(). fprintf() writes formatted text to files similar to printf(), fscanf() reads and parses formatted data from files, and file pointers connect operations to specific files. Master these operations to effectively store and retrieve data, create applications that persist information between runs, and build practical programs that interact with file systems.

#include <stdio.h>

int main() {
    FILE *file;
    char text[] = "Learning C File Handling";
    
    // Write to file
    file = fopen("demo.txt", "w");
    if (file != NULL) {
        fputs(text, file);
        fclose(file);
        printf("Data written to file\n");
    }
    
    // Read from file
    char buffer[100];
    file = fopen("demo.txt", "r");
    if (file != NULL) {
        fgets(buffer, 100, file);
        printf("Read from file: %s\n", buffer);
        fclose(file);
    }
    
    return 0;
}

Output:

Data written to file

Read from file: Learning C File Handling

🧠 Test Your Knowledge

Which function is used to open a file in C?