Binary files are made up of non-human readable characters and symbols, which require specific programs to access its contents.

Reading and writing to a binary file:

Binary files in C Language are very similar to arrays, except that arrays are designed for temporary storage of data in memory, while binary files are designed and used for permanent store data on disk. The most important difference between text files and binary a file is that in a binary file you can read, write, and search from anywhere in the file and insert structures directly into the files. The questions come in our mind: why do we need binary files in C if we already know how to handle plain text files?
Following are the list of reason why we need binary files in C:
1.faster I/O operations:
Typically, large text files contain millions of numbers. Converting 32-bit integers to readable characters takes a long time. This conversion is not necessary in case of binary files, because binary file can store data directly in bit form.

2. smaller in size than text files.
For information in the form of images, audio or video, binary file is very important. Small size means less storage and faster access of transmission of data. For example, a storage device may store vast amount of binary data rather than data in character form.
3. cannot be convert some data to character formats.
For example, code generated by C compilers after compilation.


Binary File Opening Modes

During programming in c binary file can be opened for different purposes i.e. reading, writing or both. This is specified by using file modes. Following are the list of different types of Opening mode of binary use to open a file.
rb : Open file in binary mode for reading only.
wb+ : Wb+ Open files saved in binary format for reading and writing. If the file does not available or exists it Creates the new file. If the file is present or exists all the contents available in file will be deleted.
wb : Open the file in write-only binary mode. If the file does not exist, it creates the file. If the file exists in system, it deletes the whole contents of the file.
ab+ : Open the file in binary mode to read and add data to the file . Data is appended or append to the end of the file. Creates the new file if the file does not exist.
rb+ : Open file in binary mode for both reading and writing.
ab : Opens the file in binary mode to add data. Data is appended to the end of the file. If the mentioned file does not exists then it creates the file.


Writing to a binary file:
To write contents into a binary file, we need to use the fwrite() function.
fwrite(): function is a standard file handling function available in standard library. The function is used to write binary data to the file. The function allows us to specify the number of elements to write, the file pointer where the data should be written and the size of each element.

fwrite(addressData, sizeData, numbersData, pointerToFile);

The functions take four arguments: The `fwrite()` function is a standard library function in C programming that is used to write data to a file. It is commonly used for writing binary data to files, address of data to be written in the disk 1. size of data items to be written in the disk 2. number of such type of data items 3. pointer to(address of) the file where you want to write in the file.

Write to a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>
struct employee
 {
   int empno, salary;
   float bonus;
 };
int main()
 {
   int n;
   struct employee e1;
   FILE *fptr;
   if ((fptr = fopen("employee.bin","wb")) == NULL){
   printf("Error! opening file");
   // Program exits if the file pointer returns NULL.
   exit(1);
 }
for(n =1900; n < 1905; ++n)
 {    e1.empno = n;
   e1.salary = 5*n;
   e1.bonus = e1.salary*0.10;
   fwrite(&e1, sizeof(struct employee), 1, fptr);
  }
 fclose(fptr);
  return 0;
}

In this program, we create a new file employee.bin in the C drive. We declare a structure employee with three members in int - empno, salary and bonus, and define it in the main function as e1.
Now, inside the for loop, we store the value into the file using fwrite(). The first parameter takes the address of e1 and the second parameter takes the size of the structure employee.
Since we're only inserting one instance of e1, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data. Finally, we close the file.



Reading from a binary file
To read content of binary file the Function fread() is used .
This function takes 4 arguments similar to the fwrite() function as above.
Syntax:

fread(addressData, sizeData, numbersData, pointerToFile);


Read from a binary file using fread()

#include <stdio.h>
#include <stdlib.h>
// C program to read a struct from a binary file
 typedef struct {
 int empno,salary;
    float bonus;
} employee;
int main()
{
  // open the file in rb mode
  FILE* file = fopen("employee.bin", "rb");
  // check if the file was successfully opened
  if (file == NULL) {
   perror("Error opening file");
   return 1;
  }
 // Define the struct
 employee e1;
 // Read the structs present in the file
 while (fread(&e1, sizeof(employee), 1, file) == 1)
  {
   // Process the read data (e.g., print or manipulate)
   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, you read the same file employee.bin and loop through the records one by one. In simple terms, you read one employee record from the file pointed by *fptr into the structure e1. Finally we will get all the employee records from the file.


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