Binary Files in C Programming: Read and Write Techniques
๐ In this tutorial, you will learn:
- What binary files are and why they matter in C
- The key differences between text and binary files
- How to open binary files using
fopen() with binary modes
- How to write binary data using
fwrite() with a real employee record example
- How to read binary files using
fread() step by step
What is a Binary File in C?
A binary file stores data in a format that computers can read directlyโit's not meant to be human-readable.
Unlike text files that store characters (like letters and numbers), binary files store data in raw binary format (0s and 1s).
๐ก Think of it this way: A text file is like a written note you can read.
A binary file is like a QR codeโonly computers can understand it.
Text Files vs Binary Files: What's the Difference?
| Feature |
Text Files |
Binary Files |
| Human-readable | โ
Yes | โ No |
| File size | Larger | Smaller |
| Read/write speed | Slower | Faster |
| Can store complex data | โ No | โ
Yes |
| Can be edited in Notepad | โ
Yes | โ No (garbage chars) |
Why Use Binary Files in C?
1. Faster I/O Operations โ No conversion between text and binary
2. More Compact Storage โ Takes less disk space
3. Store Complex Data โ Structures, arrays, images, audio
4. Better Security โ Not easily readable by humans
๐ Quick Start: Complete Binary File Example
Now that you understand what binary files are, here's a complete, runnable example:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int data = 12345;
int read_data;
// Write binary data
fp = fopen("data.bin", "wb");
if (fp == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fwrite(&data, sizeof(int), 1, fp);
fclose(fp);
// Read binary data
fp = fopen("data.bin", "rb");
if (fp == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
fread(&read_data, sizeof(int), 1, fp);
fclose(fp);
printf("Original: %d\nRead back: %d\n", data, read_data);
return 0;
}
Expected Output:
Original: 12345
Read back: 12345
โ
What just happened? The program stored the number 12345 in a binary file,
then read it back. You can't see the data in a text editor, but the computer understands it perfectly!
How to Read and Write Binary Files in C
Binary files in C are like arrays, but instead of temporary storage in memory, they enable permanent storage on disk. Unlike text files, binary files let you read, write, and search data from any position, making them perfect for handling large or complex data such as images, audio, or video.
Why Should You Use Binary Files in C?
- Faster Input/Output Operations: Since binary files store data in its raw form, you avoid the overhead of converting data to and from text, which speeds up processing, especially with large datasets.
- More Compact Storage: Binary files take up less space, which is crucial when working with multimedia files or storing vast amounts of data.
- Handling Raw Data: Some data, like compiled code or complex structures, cannot be easily converted to plain text, making binary files the preferred choice.
Understanding Binary File Opening Modes in C
In C, you can open binary files in different modes depending on your needs:
rb: Open for reading only in binary mode.
wb+: Open for reading and writing; creates a new file or clears existing file content.
wb: Open for writing only; creates or overwrites an existing file.
ab+: Open for appending (reading and writing); creates file if it doesn't exist.
rb+: Open for both reading and writing.
ab: Append data to the end of the file; creates if not exists.
Writing Data to a Binary File in C
To write data into a binary file in C, you typically use the fwrite() function:
fwrite(pointerToData, sizeOfData, numberOfItems, filePointer);
This function takes four parameters:
pointerToData: The address of the data you want to write.
sizeOfData: The size in bytes of each data item.
numberOfItems: How many data items you want to write.
filePointer: The pointer to the open file.
How to Write Employee Data to a Binary File in C Using fwrite()
Learn how to efficiently store employee records in a binary file in C using the fwrite() function. Writing data in binary format allows for fast, compact storage of complex data structures like employee information, including employee number, salary, and bonus.
#include <stdio.h>
#include <stdlib.h>
// Define the employee structure
struct employee {
int empno;
int salary;
float bonus;
};
int main() {
int n;
struct employee e1;
FILE *fptr;
// Open the binary file for writing
if ((fptr = fopen("employee.bin", "wb")) == NULL) {
printf("Error! Unable to open file.\n");
exit(1);
}
// Generate and write employee data to the binary file
for (n = 1900; n < 1905; ++n) {
e1.empno = n;
e1.salary = 5 * n;
e1.bonus = e1.salary * 0.10;
// Write the employee data to the binary file
fwrite(&e1, sizeof(struct employee), 1, fptr);
}
// Close the file after writing
fclose(fptr);
return 0;
}
This program creates a binary file named employee.bin in your project directory. It defines an employee structure with three members: empno, salary, and bonus. Inside the for loop, it populates this structure with sample data and writes each record to the binary file using fwrite(). The data is stored efficiently in binary format, making it suitable for applications requiring fast data access and minimal storage space.
In this example, the program creates a new file called employee.bin. The employee structure holds employee number, salary, and bonus. The fwrite() function takes the address of e1, the size of the structure, the number of items to write (1 in this case), and the file pointer fptr. After writing all records, the file is closed with fclose().
๐ป Practice Exercise
Challenge: Create a program that writes 10 integer values (1 to 10) to a binary file and then reads them back. Use a loop with fwrite() and fread().
๐ Click to Show Solution
#include <stdio.h>
int main() {
FILE *fp;
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int read_arr[10];
// Write array to binary file
fp = fopen("numbers.bin", "wb");
if (fp == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fwrite(arr, sizeof(int), 10, fp);
fclose(fp);
// Read array from binary file
fp = fopen("numbers.bin", "rb");
if (fp == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
fread(read_arr, sizeof(int), 10, fp);
fclose(fp);
// Display read data
printf("Numbers read from binary file:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", read_arr[i]);
}
printf("\n");
return 0;
}
Expected Output:
Numbers read from binary file:
1 2 3 4 5 6 7 8 9 10
Reading Data from a Binary File in C Using fread()
Learn how to read employee records from a binary file in C using the fread() function. This function allows you to efficiently retrieve data stored in binary format, such as structures containing employee information.
Example: Reading Employee Data from a Binary File in C with fread()
#include <stdio.h>
#include <stdlib.h>
// Define the employee structure
typedef struct {
int empno;
int salary;
float bonus;
} employee;
int main() {
// Open the binary file in read mode
FILE* file = fopen("employee.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Declare a structure variable to hold read data
employee e1;
// Read employee records one by one until end of file
while (fread(&e1, sizeof(employee), 1, file) == 1) {
// Process the read data (e.g., print)
printf("Employee No: %d, Salary: %d, Bonus: %.2f\n", e1.empno, e1.salary, e1.bonus);
}
// Close the file
fclose(file);
return 0;
}
In this program, the file employee.bin is opened in binary read mode ("rb"). The program reads each employee record into the employee structure variable e1 using fread(). The loop continues until all records are read, allowing you to process or display the employee information as needed.
Frequently Asked Questions About Binary Files in C
1. What is the difference between text and binary files in C?
Text files store data as human-readable characters (ASCII), while binary files store data in raw binary format. Binary files are more compact, faster to read/write, and can store complex data structures directly. However, text files are easier to debug and view with any text editor.
2. Can I mix text and binary operations on the same file?
No, you should never mix text and binary operations on the same file. Always use the correct mode consistentlyโuse "rb" and "wb" for binary files, and "r" and "w" for text files. Mixing modes can lead to data corruption and undefined behavior.
3. Why does my binary file contain non-printable characters?
Binary files store data in machine-readable formatโthey're not meant to be viewed as text. The "garbage" or "non-printable" characters you see are actually the raw binary data (1s and 0s) displayed as characters. This is normal and expected behavior.
4. Why should I use fwrite() instead of fprintf()?
fwrite() writes raw binary data directly, which is faster and more compact. fprintf() converts data to text format, which is slower and takes more space. Use fwrite() for binary files and fprintf() for text files.
5. What happens if I open a binary file in text mode?
Opening a binary file in text mode ("r" or "w") can corrupt the data. On Windows, text mode converts newline characters (\r\n to \n), which can corrupt binary data. Always use "rb" and "wb" for binary files.
๐ก Tip: Always check return values of fopen(), fread(), and fwrite() to handle errors gracefully.
Previous Topic: -->> files examples in C ||
Next topic: -->> Count word line in file
๐ Explore More Topics
๐๏ธ SQL Interview Questions & Answers
๐ Python Interview Questions & Answers
โ Java Interview Questions & Answers