C Programming Reading And Writing To Files Fread Fwrite Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of C Programming Reading and Writing to Files fread, fwrite

C Programming Reading and Writing to Files: fread and fwrite

1. Understanding File Handling in C

Before diving into fread and fwrite, let's briefly review the basics of file handling in C. Files are stored on secondary storage and can be accessed randomly or sequentially. The C standard library provides functions to open, read, write, and close files.

Here’s a quick reminder of the primary file handling functions:

  • FILE *fopen(const char *filename, const char *mode);
  • int fclose(FILE *stream);

The fopen function opens a file and returns a pointer to a FILE structure, which is used for further operations on the file. The mode parameter specifies the purpose of opening the file (e.g., "r" for reading, "w" for writing, "a" for appending).

2. Writing Data to Files Using fwrite

The fwrite function writes a specified number of elements of a specified size from a memory location to a file. The function prototype is as follows:

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  • ptr: Pointer to the block of memory from which data is to be written.
  • size: Size in bytes of each element to be written.
  • nmemb: Number of elements to be written.
  • stream: Pointer to FILE structure where data will be written.

The function returns the number of elements successfully written. If this number is less than nmemb, an error has occurred.

Example:

#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    FILE *file = fopen("output.bin", "wb");

    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    size_t written = fwrite(numbers, sizeof(int), 5, file);
    if (written != 5) {
        perror("Error writing to file");
        fclose(file);
        return 1;
    }

    fclose(file);
    printf("Data written successfully\n");
    return 0;
}

In this example, an array of integers is written to a binary file named "output.bin". The file is opened in binary mode ("wb"). The sizeof(int) ensures that the correct number of bytes is written for each integer. The result is verified by comparing the return value of fwrite with the expected number of elements.

3. Reading Data from Files Using fread

The fread function reads a specified number of elements of a specified size from a file into a memory location. The function prototype is:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
  • ptr: Pointer to the block of memory where data will be read.
  • size: Size in bytes of each element to be read.
  • nmemb: Number of elements to be read.
  • stream: Pointer to FILE structure from which data will be read.

The function returns the number of elements successfully read. If this number is less than nmemb, the end-of-file or an error has occurred.

Example:

#include <stdio.h>

int main() {
    int numbers[5];
    FILE *file = fopen("output.bin", "rb");

    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    size_t read = fread(numbers, sizeof(int), 5, file);
    if (read != 5) {
        perror("Error reading from file");
        fclose(file);
        return 1;
    }

    fclose(file);

    printf("Data read successfully:\n");
    for (size_t i = 0; i < 5; ++i) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

In this example, the previously written binary file "output.bin" is opened in binary read mode ("rb"). The fread function reads the integers back into the numbers array. The result is verified by comparing the return value with the expected number of elements. The integers are then printed to the console.

4. Error Handling

When working with file I/O operations, error handling is essential to prevent crashes and ensure data integrity. Functions like fopen, fwrite, and fread return specific values or pointers that can be checked for success or failure. Using the perror function, you can print a human-readable error message describing the last error encountered.

Important Points to Remember:

  • Use "wb" and "rb" modes when reading/writing binary files to ensure correct data representation.
  • Always check the return values of fopen, fwrite, and fread to handle errors appropriately.
  • Close files using fclose to free up system resources and ensure data is written if necessary.
  • Consider using buffered I/O functions (fgets, fscanf) for text files to improve performance and readability.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement C Programming Reading and Writing to Files fread, fwrite

Example 1: Writing Binary Data to a File

In this example, we'll write an array of integers to a file in binary format using fwrite.

Step 1: Include Necessary Headers

We need the following header files:

  • stdio.h: For input/output functions like fopen, fclose, fwrite.
#include <stdio.h>

Step 2: Define the Main Function

Create the main function where the operations will take place.

int main() {
    FILE *file;
    int numbers[] = {1, 2, 3, 4, 5};
    int nNumbers = sizeof(numbers) / sizeof(numbers[0]);
    
    // Open file in binary write mode
    file = fopen("numbers.bin", "wb"); 
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    
    // Write numbers to file using fwrite
    fwrite(numbers, sizeof(int), nNumbers, file);
    
    // Close the file
    fclose(file);
    
    printf("Data written successfully.\n");
    
    return 0;
}

Step 3: Compile and Run the Program

Save the program as write_numbers.c and compile it using a C compiler:

gcc write_numbers.c -o write_numbers
./write_numbers

This will create a file named numbers.bin containing the binary representation of the integers 1 through 5.

Example 2: Reading Binary Data from a File

In this example, we'll read the integers from the file created in Example 1 using fread.

Step 1: Include Necessary Headers

Again, we need stdio.h for input/output functions.

#include <stdio.h>

Step 2: Define the Main Function

Create the main function to read data from numbers.bin.

int main() {
    FILE *file;
    int numbers[5];
    int nNumbersRead;
    
    // Open file in binary read mode
    file = fopen("numbers.bin", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    
    // Read numbers from file using fread
    nNumbersRead = fread(numbers, sizeof(int), 5, file);
    if (nNumbersRead != 5) {
        fprintf(stderr, "Error reading file. Expected to read %d numbers but read %d.\n", 5, nNumbersRead);
        fclose(file);
        return 1;
    }
    
    // Print the numbers read from the file
    printf("Numbers read from file:\n");
    for (int i = 0; i < nNumbersRead; i++) {
        printf("%d\n", numbers[i]);
    }

    // Close the file
    fclose(file);

    return 0;
}

Step 3: Compile and Run the Program

Save this program as read_numbers.c and compile it using your C compiler:

gcc read_numbers.c -o read_numbers
./read_numbers

This will print the numbers 1 through 5 read from the numbers.bin file.

Explanation

Writing to a File (fwrite)

  • fopen(filename, mode): Opens the file named filename in the specified mode. In this case, "wb" means open in binary write mode.
  • fwrite(data, size, count, file): Writes count elements of size size bytes, from the memory address data to the file.
  • sizeof(int): The size of one integer in bytes.
  • sizeof(numbers) / sizeof(numbers[0]): This calculates the number of integers in the array numbers.
  • fclose(file): Closes the file once we're done with it, which is necessary to free up system resources.

Reading from a File (fread)

  • fopen(filename, mode): Opens the file named filename in binary read mode ("rb").
  • fread(out_data, size, count, file): Reads count elements of size size bytes from file into the memory location pointed to by out_data.
  • perror(string): Prints a human-readable error message to stderr when a system call fails, along with the string provided.
  • fprintf(stderr, string, ...): Prints formatted output to the standard error stream, useful for debugging error messages.
  • fclose(file): It is crucial to close the file to ensure all data is properly written and to release any system resources.

You May Like This Related .NET Topic

Login to post a comment.