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:
#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:
- We define a structure
Data
with two members:id
(an integer) andvalue
(a float). - We create an instance
d
and initialize it with sample values. - The file is opened in binary write mode (
"wb"
) usingfopen
and assigned to the file pointerfp
. - Error checking is performed to ensure the file was opened successfully.
- The
fwrite
function writes the structured
to the file; the parameters include the address ofd
, the size of theData
structure, and the number of elements to write (1
). - 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:
#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:
- An integer array
numbers[]
is declared and initialized with 5 elements. - The number of elements in the array is calculated using
sizeof(numbers) / sizeof(numbers[0])
and stored insize
. - The file
numbers.bin
is opened in binary write mode ("wb"
) withfopen
. - Error checking is performed to ensure the file opened successfully.
- The
fwrite
function writes the entire array to the file. The parameters include the array namenumbers
, the size of an integer (sizeof(int)
), and the number of elements (size
). - 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:
#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:
- A structure
Record
is defined with membersid
andmeasurement
. - An instance
newRecord
is created and initialized with sample data. - The file
records.bin
is opened in append binary mode ("ab"
) usingfopen
, which preserves existing data while allowing new data to be added. - Error checking is done to ensure the file is successfully opened.
- The
fwrite
function writes thenewRecord
data to the file, appending it to any existing binary data. - 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:
- Example 1: Writing a structure to a binary file using
fwrite
. - Example 2: Writing an integer array to a binary file.
- Example 3: Appending binary data to an existing file.