Write Binary Data to a File in C

To write binary data to a file in C, open a file in binary mode and write data using functions like fwrite and system-level functions.


Example 1: Writing a Struct to a Binary File Using fwrite

In this example, we will create a simple structure, populate it with data, and write the entire structure to a binary file using the fwrite function.

Explanation:

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

typedef struct {
    int id;
    float value;
} Data;

int main() {
    Data d = {1, 3.14f};
    FILE *fp = fopen("data.bin", "wb");

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

    // Write the struct to the file
    fwrite(&d, sizeof(Data), 1, fp);
    fclose(fp);

    return 0;
}

Explanation:

  1. We define a structure Data with two members: id (an integer) and value (a float).
  2. We create an instance d and initialize it with sample values.
  3. The file is opened in binary write mode ("wb") using fopen and assigned to the file pointer fp.
  4. Error checking is performed to ensure the file was opened successfully.
  5. The fwrite function writes the structure d to the file; the parameters include the address of d, the size of the Data structure, and the number of elements to write (1).
  6. Finally, the file is closed using fclose.

Output:

This program does not produce console output but creates a binary file named data.bin containing the binary representation of the structure.

Example 2: Writing an Integer Array to a Binary File

In this example, we will write an array of integers to a binary file using fwrite. This is useful when you want to store multiple data values in binary format.

Explanation:

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

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    FILE *fp = fopen("numbers.bin", "wb");

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

    // Write the integer array to the file
    fwrite(numbers, sizeof(int), size, fp);
    fclose(fp);

    return 0;
}

Explanation:

  1. An integer array numbers[] is declared and initialized with 5 elements.
  2. The number of elements in the array is calculated using sizeof(numbers) / sizeof(numbers[0]) and stored in size.
  3. The file numbers.bin is opened in binary write mode ("wb") with fopen.
  4. Error checking is performed to ensure the file opened successfully.
  5. The fwrite function writes the entire array to the file. The parameters include the array name numbers, the size of an integer (sizeof(int)), and the number of elements (size).
  6. The file is then closed using fclose.

Output:

This program creates a binary file named numbers.bin containing the binary representation of the integer array.

Example 3: Appending Binary Data to an Existing File

In this example, we will open an existing binary file in append mode and add more binary data to it using fwrite. This approach is useful when you need to add data to a file without overwriting its current contents.

Explanation:

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

typedef struct {
    int id;
    double measurement;
} Record;

int main() {
    Record newRecord = {2, 25.678};
    FILE *fp = fopen("records.bin", "ab"); // Open file in append binary mode

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

    // Append newRecord to the existing binary file
    fwrite(&newRecord, sizeof(Record), 1, fp);
    fclose(fp);

    return 0;
}

Explanation:

  1. A structure Record is defined with members id and measurement.
  2. An instance newRecord is created and initialized with sample data.
  3. The file records.bin is opened in append binary mode ("ab") using fopen, which preserves existing data while allowing new data to be added.
  4. Error checking is done to ensure the file is successfully opened.
  5. The fwrite function writes the newRecord data to the file, appending it to any existing binary data.
  6. The file is then closed using fclose.

Output:

This program appends a binary record to the file records.bin. There is no direct console output, but the file is updated with the new binary data.

Conclusion

In this tutorial, we explored multiple scenarios for writing binary data to a file in C:

  1. Example 1: Writing a structure to a binary file using fwrite.
  2. Example 2: Writing an integer array to a binary file.
  3. Example 3: Appending binary data to an existing file.