Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Binary File I/O in C

Introduction

File handling is a critical part of any programming language. In C, file handling is simple and effective. This tutorial focuses on binary file I/O in C. Binary files store data in the same format in which the data is held in memory, enabling efficient read and write operations.

Opening Files

To perform binary file operations, you need to open the file in binary mode. The function fopen() is used for this purpose. The mode "rb" is used to open a file for reading in binary mode, and "wb" is used to open a file for writing in binary mode.

Example:

FILE *file = fopen("data.bin", "wb");

Writing to a Binary File

To write data to a binary file, you can use the fwrite() function. This function writes data from a buffer to the file.

Example:

FILE *file = fopen("data.bin", "wb");
int num = 1234;
fwrite(&num, sizeof(int), 1, file);
fclose(file);

Reading from a Binary File

To read data from a binary file, you can use the fread() function. This function reads data from the file into a buffer.

Example:

FILE *file = fopen("data.bin", "rb");
int num;
fread(&num, sizeof(int), 1, file);
printf("Number: %d\n", num);
fclose(file);

Checking for Errors

It is essential to check for errors while performing file operations. The ferror() function can be used to check for errors during file operations.

Example:

FILE *file = fopen("data.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return -1;
}
int num;
fread(&num, sizeof(int), 1, file);
if (ferror(file)) {
perror("Error reading file");
}
fclose(file);

Closing Files

After performing file operations, it is crucial to close the file using the fclose() function to free up resources.

Example:

FILE *file = fopen("data.bin", "rb");
// Perform file operations
fclose(file);

Full Example

Here is a complete example demonstrating reading and writing to a binary file:

#include <stdio.h>

int main() {
FILE *file;
int num;

// Writing to a binary file
file = fopen("data.bin", "wb");
if (file == NULL) {
perror("Error opening file for writing");
return -1;
}
num = 1234;
fwrite(&num, sizeof(int), 1, file);
fclose(file);

// Reading from a binary file
file = fopen("data.bin", "rb");
if (file == NULL) {
perror("Error opening file for reading");
return -1;
}
fread(&num, sizeof(int), 1, file);
if (ferror(file)) {
perror("Error reading file");
} else {
printf("Number: %d\n", num);
}
fclose(file);

return 0;
}