C fread() Function

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.

Table of Contents

  1. Introduction
  2. fread() Function Syntax
  3. Examples
    • Reading an Array of Integers
    • Reading a Structure from a Binary File
  4. Real-World Use Case
  5. Conclusion

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.

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 is essential for reading binary data from files in C. It allows you to read a specified number of elements of a specified size from a given stream into a block of memory. By understanding and using this function, you can efficiently manage binary file input operations in your C programs. Always ensure that the number of elements read matches the expected number to handle errors and end-of-file conditions correctly.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top