Binary files contain non-human readable characters and symbols, accessible with specific programs

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); // Exit if the file cannot be opened } // 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().


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.


Previous Topic: -->> files examples in C   ||   Next topic: -->> Count word line in file