Reading and Writing Binary Files in C


Introduction

Reading and writing binary files in C allows you to work with data in its raw, binary form. This can be useful for tasks like reading and writing image files, serialization, and more. In this guide, we'll explore the concepts of reading and writing binary files in C, explain how it works, and provide sample code to illustrate their usage.


File Handling in C

C provides a set of functions to handle files, and this includes working with binary files. Common functions for file handling in C include

fopen()
,
fread()
,
fwrite()
, and
fclose()
. When working with binary files, you need to specify the file mode as binary, such as
"wb"
for writing and
"rb"
for reading.


Sample Code

Let's explore some examples of reading and writing binary files in C:


Writing Binary Data to a File

#include <stdio.h>
int main() {
FILE *file;
char data[] = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // Binary data
file = fopen("binary_file.bin", "wb");
if (file != NULL) {
fwrite(data, sizeof(char), sizeof(data), file);
fclose(file);
printf("Binary data written to the file.\\n");
} else {
printf("Failed to open the file.\\n");
}
return 0;
}

Reading Binary Data from a File

#include <stdio.h>
int main() {
FILE *file;
char data[5]; // Binary data will be read into this array
file = fopen("binary_file.bin", "rb");
if (file != NULL) {
fread(data, sizeof(char), sizeof(data), file);
fclose(file);
printf("Binary data read from the file: ");
for (int i = 0; i < sizeof(data); i++) {
printf("%c", data[i]);
}
printf("\\n");
} else {
printf("Failed to open the file.\\n");
}
return 0;
}

Conclusion

Reading and writing binary files in C is a valuable skill for working with raw data. This guide introduced the concept of reading and writing binary files, explained how it works in C, and provided sample code to demonstrate their usage. As you continue your C programming journey, you'll find this knowledge helpful for handling various types of data in its binary form.