C fread() Function | Read Binary Data from Files

Introduction

The fread() function is used for reading binary data from files. It reads a specified number of elements of a specified size from a given stream into a block of memory.

fread() Function Syntax

The syntax for the fread() function is as follows:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Parameters:

  • ptr: A pointer to a block of memory where the read data will be stored.
  • size: The size in bytes of each element to be read.
  • nmemb: The number of elements, each one with a size of size bytes.
  • stream: A pointer to a FILE object that specifies an input stream.

Returns:

  • The function returns the total number of elements successfully read, which may be less than nmemb if an error or end-of-file condition occurs.

Understanding fread()

The fread() function reads data from the specified stream and stores it in the block of memory pointed to by ptr. It reads up to nmemb elements, each of size bytes. The function stops reading when it has read nmemb elements, or if an error or end-of-file condition is encountered.

Examples

Reading an Array of Integers

To demonstrate how to use fread() to read an array of integers from a binary file, we will write a simple program.

Example

#include <stdio.h>

int main() {
    FILE *file;
    int numbers[5];

    // Open the file for reading
    file = fopen("numbers.bin", "rb");
    if (file == NULL) {
        printf("Error: Could not open file for reading.\n");
        return 1;
    }

    // Read data from the file into the array
    size_t elementsRead = fread(numbers, sizeof(int), 5, file);
    if (elementsRead != 5) {
        printf("Error: Could not read the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    // Print the read data
    for (int i = 0; i < 5; i++) {
        printf("Number %d: %d\n", i + 1, numbers[i]);
    }

    return 0;
}

Output (assuming numbers.bin contains five integers):

Number 1: 10
Number 2: 20
Number 3: 30
Number 4: 40
Number 5: 50

Reading a Structure from a Binary File

This example demonstrates how to use fread() to read a structure from a binary file.

Example

#include <stdio.h>

typedef struct {
    char name[50];
    int age;
    float salary;
} Employee;

int main() {
    FILE *file;
    Employee emp;

    // Open the file for reading
    file = fopen("employee.bin", "rb");
    if (file == NULL) {
        printf("Error: Could not open file for reading.\n");
        return 1;
    }

    // Read data from the file into the structure
    size_t elementsRead = fread(&emp, sizeof(Employee), 1, file);
    if (elementsRead != 1) {
        printf("Error: Could not read the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    // Print the read data
    printf("Name: %s\n", emp.name);
    printf("Age: %d\n", emp.age);
    printf("Salary: %.2f\n", emp.salary);

    return 0;
}

Output (assuming employee.bin contains one Employee structure):

Name: Ramesh Fadatare
Age: 30
Salary: 60000.00

Real-World Use Case

Reading Configuration Data

In real-world applications, the fread() function can be used to read configuration data from a binary file into memory.

Example

#include <stdio.h>

typedef struct {
    char url[100];
    int timeout;
    int maxConnections;
} Config;

int main() {
    FILE *file;
    Config config;

    // Open the file for reading
    file = fopen("config.bin", "rb");
    if (file == NULL) {
        printf("Error: Could not open file for reading.\n");
        return 1;
    }

    // Read data from the file into the configuration structure
    size_t elementsRead = fread(&config, sizeof(Config), 1, file);
    if (elementsRead != 1) {
        printf("Error: Could not read the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    // Print the read data
    printf("URL: %s\n", config.url);
    printf("Timeout: %d\n", config.timeout);
    printf("Max Connections: %d\n", config.maxConnections);

    return 0;
}

Output (assuming config.bin contains one Config structure):

URL: http://example.com
Timeout: 5000
Max Connections: 100

Conclusion

The fread() function in C is a standard library function that reads data from a given stream into an array. It is part of the C standard library (stdio.h) and is commonly used for binary file input operations.

Comments