C

File Operations in C: fopen, fclose, fread, and fwrite

In C programming, a File is a place on the disk where data is stored permanently. While variables and arrays store data in RAM (volatile memory), file operations allow a program to save data so it persists even after the program terminates or the computer is turned off.

C treats all device interaction as a Stream—a sequence of bytes. File handling involves connecting a stream to a specific file on your storage device.

1. The Theory: Buffered I/O and the FILE Pointer

C uses a structure called FILE (defined in <stdio.h>) to manage file streams. This structure contains information about the file's current position, its buffer, and its status (error/end-of-file).

Why Buffered?

Directly accessing the hard drive for every single byte is extremely slow. C uses Buffered I/O, meaning it reads or writes a large "chunk" of data into a temporary memory area (buffer). The program then interacts with this buffer, and the operating system synchronizes the buffer with the disk when it's full or when the file is closed.

2. Opening and Closing Files

Before performing any operation, you must establish a connection to the file.

A. fopen() – Opening a File

This function creates a link between your program and the physical file.

  • Syntax: FILE *fp = fopen("filename.txt", "mode");

  • Modes:

    • "r": Read mode. Fails if the file doesn't exist.

    • "w": Write mode. Creates a new file or overwrites an existing one.

    • "a": Append mode. Adds data to the end of an existing file.

    • "rb", "wb", "ab": Same as above but for binary files.

B. fclose() – Closing a File

Closing a file is mandatory. It ensures that any data remaining in the buffer is written to the disk (flushed) and releases the memory used by the FILE structure.

  • Syntax: fclose(fp);

3. Binary File Operations: fread and fwrite

While fprintf and fscanf are used for text files (human-readable), fread and fwrite are used for Binary Files. Binary files are more efficient for storing large amounts of data, like structures or arrays, because they store the data exactly as it appears in memory.

A. fwrite() – Writing Blocks

  • Theory: It copies a block of memory from the RAM directly to the file.

  • Syntax: fwrite(address_of_data, size_of_element, number_of_elements, file_pointer);

  • Example: fwrite(&student1, sizeof(struct Student), 1, fp);

B. fread() – Reading Blocks

  • Theory: It reads a block of data from the file and places it into a variable or array in memory.

  • Syntax: fread(address_of_buffer, size_of_element, number_of_elements, file_pointer);

  • Return Value: It returns the number of items successfully read. If this is less than requested, you’ve reached the end of the file (EOF) or encountered an error.

4. Practical Code Example

This program demonstrates saving a structure to a binary file and then reading it back.


#include <stdio.h>
#include <stdlib.h>

struct Record {
    int id;
    char name[20];
};

int main() {
    FILE *fp;
    struct Record r1 = {1, "EMBLAb User"}, r2;

    // 1. OPEN file for writing in binary mode
    fp = fopen("data.bin", "wb");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // 2. WRITE data to the file
    fwrite(&r1, sizeof(struct Record), 1, fp);
    fclose(fp);
    printf("Record saved to binary file.\n");

    // 3. OPEN file for reading in binary mode
    fp = fopen("data.bin", "rb");
    if (fp == NULL) return 1;

    // 4. READ data from the file into r2
    fread(&r2, sizeof(struct Record), 1, fp);
    
    printf("Read from file: ID: %d, Name: %s\n", r2.id, r2.name);

    fclose(fp);
    return 0;
}

5. Critical Theory: File Positioning and Safety

End of File (EOF) and Errors

  • feof(fp): Returns true if the program has tried to read past the end of the file.

  • ferror(fp): Checks if a hardware or permissions error occurred during the last operation.

File Offsets (fseek)

Inside every open file, there is a "cursor" or "file position indicator." Every time you read or write, this cursor moves forward.

  • fseek(fp, offset, origin): Allows you to move this cursor to a specific byte, enabling Random Access. You can jump to the middle of a file without reading everything before it.

6. Summary Table

FunctionPurposeBest Used For
fopenOpens a stream to a file.Initialization of all file I/O.
fcloseCloses stream and flushes buffer.Cleanup and data integrity.
fwriteWrites raw bytes from RAM to disk.Saving arrays and structures.
freadReads raw bytes from disk to RAM.Loading saved data/records.
fseekMoves the file cursor.Navigating large database files.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now