Read Binary Data from a File in C

To read binary data from a file in C, you can use fread() function, and read data into structures.


Example 1: Reading Binary Data Using fread()

In this example, we will read binary data from a file using the fread() function. The program opens a binary file, reads a fixed number of bytes into a buffer, and then prints the data as hexadecimal values.

main.c

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

int main() {
    FILE *file = fopen("data.bin", "rb"); // Open the binary file in read mode
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }
    
    // Allocate a buffer to hold 16 bytes of binary data
    unsigned char buffer[16];
    size_t bytesRead = fread(buffer, sizeof(unsigned char), 16, file);
    
    // Print the bytes in hexadecimal format
    printf("Read %zu bytes:\n", bytesRead);
    for (size_t i = 0; i < bytesRead; i++) {
        printf("%02X ", buffer[i]);
    }
    printf("\n");
    
    fclose(file); // Close the file
    return 0;
}

Explanation:

  1. FILE *file: A pointer used to handle the file stream. The file “data.bin” is opened in binary read mode ("rb").
  2. fopen(): Opens the file. If the file is not found, an error message is displayed using perror().
  3. unsigned char buffer[16]: A buffer allocated to store 16 bytes of data read from the file.
  4. fread(): Reads up to 16 bytes from the file into the buffer. It returns the number of bytes actually read.
  5. printf(): Used to display the number of bytes read and to print each byte in hexadecimal format.
  6. fclose(): Closes the file stream once reading is complete.

Output:

Read 16 bytes:
3A 5F B2 4C 00 FF 10 22 3D 4E 6F 88 99 AA BB CC

Example 2: Reading Binary Data into a Structure

In this example, we demonstrate how to read binary data into a structure. The program defines a structure to hold information, opens a binary file, reads the structure data using fread(), and then prints the structure members.

main.c

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

typedef struct {
    int id;
    float value;
    char name[20];
} Data;

int main() {
    FILE *file = fopen("structdata.bin", "rb"); // Open the binary file in read mode
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }
    
    Data record;
    size_t bytesRead = fread(&record, sizeof(Data), 1, file);
    
    if (bytesRead == 1) {
        printf("ID: %d\n", record.id);
        printf("Value: %.2f\n", record.value);
        printf("Name: %s\n", record.name);
    } else {
        printf("Error reading structure from file.\n");
    }
    
    fclose(file); // Close the file
    return 0;
}

Explanation:

  1. typedef struct { ... } Data;: Defines a structure named Data with members id, value, and name.
  2. FILE *file: Opens the binary file structdata.bin in read mode ("rb").
  3. fread(): Reads one instance of the Data structure from the file into the variable record.
  4. Checks if the number of bytes read equals 1 to ensure successful reading.
  5. printf(): Prints the values of record.id, record.value, and record.name to the console.
  6. fclose(): Closes the file after reading is complete.

Output:

ID: 101
Value: 45.67
Name: ExampleRecord

Conclusion

In this tutorial, we covered two approaches to reading binary data from files in C:

  1. Using fread() to read raw binary data into a buffer and printing it in hexadecimal format.
  2. Reading binary data directly into a defined structure, allowing structured data retrieval and easy access to its members.