C and C++ Binary Files
What is a binary file?
A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are different operations that are performed on the binary file in c and c++, such as writing and reading.
Writing
For writing any binary file, we use writing operations. This writing operation is done to write a number on the given stream. The position from where to write is given to the write function as a pointer. If the pointer points to the end of the file, the file will be extended. If the pointers are pointed to the middle of the file, the file characters are overwritten.
Reading
To read the content in the file read operator is used. The reading process will take place from the read function's pointer. For reading also pointer is used.
Code to write text in a file in C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
file.open("binSample.dat");
if(!file.is_open())
{
cout<<"Unable to open the file\n";
return 0;
}
string myStr = "This string is written to the binary file.";
file.write(myStr.data(), myStr.size());
file.close();
return 0;
}
Explanation:
The above code is written to write the data into a file. To do this, we have used a file. The write function is a part of the fstream header file. Now we need to open the file using the open keyword. A new file will be created in a path if the file is not found. When using the write function, we have written the file with a string stored in the mystr variable. After opening the file, we need to close the file, which is done using the close operator.
Write operation can be done using many keywords such as put() etc.
Example for writing a file using the put() function:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
file.open("binSample_2.dat");
if(!file.is_open())
{
cout<<"Unable to open the file\n";
return 0;
}
string myStr = "This string is written to the binary file.";
for(int i=0;i<myStr.size();i++)
{
file.put(myStr[i]);
}
file.close();
return 0;
}
Explanation:
The above code is written to write the data into a file. To do this, we have used file.put function, which is a part of the fstream header file. In the same manner, as the previous example, we have written the content in the file using the put() function. Now we need to open the file using the open keyword. A new file will be created in a path if the file is not found. Using the put() function inside the loop, we have written the array values in the file. After opening the file, we need to close the file, which is done using the close operator.
Example: Writing using << operator.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
file.open("binSample_3.dat");
if(!file.is_open())
{
cout<<"Unable to open the file\n";
return 0;
}
string myStr = "This string is written to the binary file.";
file<<myStr;
file.close();
return 0;
}
Explanation:
Similarly, as in the previous example, we have used the << function to write in the file. The above code is written to write the data into a file. To do this, we have used << function. Now we need to open the file using the open keyword. If the file is not found, then unable to open the file will be displayed. So we need to create the file in the path before writing the content. Using the write function, we have written the file with a string stored in the mystr variable. After opening the file, we need to close the file, which is done using the close operator.
Code to write text in a file in C
Example: Writing a binary file in C
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
Explanation:
The above example is similar to the previous examples we wrote in c++. But here we are writing the code for C language. The procedure is the same, but we need to use f before all the keywords, such as fwrite, fopen, etc...
Reading binary files in c:
To read a binary file in C, we need to use the fread function, which is part of the standard library of input and output
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
//fopen is used to open the file
if ((fptr = fopen("C:\ Users\ out","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
//fscanf function is used to read the data in the file
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
Explanation:
The above code is written to read the data in the file. Using the fscanf keyword, we have read the content in the file. Similarly, we can use fgetchar() and fputc() to read the data. So here we have opened the file located in the path. A file must be created to read the data. From the opened file, we have read the data. There is no data in the file, so there will be no output.
Example: 1 Code for reading files
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student wstu[3];
wstu[0].roll = 1;
wstu[0].name = "sai";
wstu[1].roll = 2;
wstu[1].name = "kiran";
wstu[2].roll = 3;
wstu[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &wstu[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1;
}
ifstream rf("student.dat", ios::out | ios::binary);
if(!rf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student rstu[3];
for(int i = 0; i < 3; i++)
rf.read((char *) &rstu[i], sizeof(Student));
rf.close();
if(!rf.good()) {
cout << "Error occurred at reading time!" << endl;
return 1;
}
cout<<"Student's Details:"<<endl;
for(int i=0; i < 3; i++) {
cout << "Roll No: " << wstu[i].roll << endl;
cout << "Name: " << wstu[i].name << endl;
cout << endl;
}
return 0;
}
Output:

Explanation:
The above code reads and writes the data into a file. In the above code, we used the read and write function. We have created a structure data type, a user-defined data type, and we used that data type in the main function. In the main function, we have created a file, and then, using the struct keyword, we have written the student's details in the files. After that, using the read function, we printed the details of the students as the output.
As we have discussed earlier, we need to close the files once we have opened them, so this has done using the close function.
Example:2 For taking input from the user and writing in the file and then reading
#include <iostream>
#include <fstream>
#define FILE_NAME "emp.dat"
using namespace std;
//class employee declaration
class Employee {
private :
int empID;
char empName[100] ;
char designation[100];
int ddj,mmj,yyj;
int ddb,mmb,yyb;
public :
//function to read employee details
void readEmployee(){
cout<<"EMPLOYEE DETAILS"<<endl;
cout<<"ENTER EMPLOYEE ID : " ;
cin>>empID;
cin.ignore(1);
cout<<"ENTER NAME OF THE EMPLOYEE : ";
cin.getline(empName,100);
cout<<"ENTER DESIGNATION : ";
cin.getline(designation,100);
cout<<"ENTER DATE OF JOIN:"<<endl;
cout<<"DATE : "; cin>>ddj;
cout<<"MONTH: "; cin>>mmj;
cout<<"YEAR : "; cin>>yyj;
cout<<"ENTER DATE OF BIRTH:"<<endl;
cout<<"DATE : "; cin>>ddb;
cout<<"MONTH: "; cin>>mmb;
cout<<"YEAR : "; cin>>yyb;
}
//function to write employee details
void displayEmployee(){
cout<<"EMPLOYEE ID: "<<empID<<endl
<<"EMPLOYEE NAME: "<<empName<<endl
<<"DESIGNATION: "<<designation<<endl
<<"DATE OF JOIN: "<<ddj<<"/"<<mmj<<"/"<<yyj<<endl
<<"DATE OF BIRTH: "<<ddb<<"/"<<mmb<<"/"<<yyb<<endl;
}
};
int main(){
//object of Employee class
Employee emp;
//read employee details
emp.readEmployee();
//write the object into the file
fstream file;
file.open(FILE_NAME,ios::out|ios::binary);
if(!file){
cout<<"Error in creating file...\n";
return -1;
}
file.write((char*)&emp,sizeof(emp));
file.close();
cout<<"Date saved into file the file.\n";
//open the file again
file.open(FILE_NAME,ios::in|ios::binary);
if(!file){
cout<<"Error in opening file...\n";
return -1;
}
if(file.read((char*)&emp,sizeof(emp))){
cout<<endl<<endl;
cout<<"Data extracted from file..\n";
//print the object
emp.displayEmployee();
}
else{
cout<<"Error in reading data from file...\n";
return -1;
}
file.close();
return 0;
}
Output:

Explanation:
The above code is written to write the data into the files and then finally read the file. In the above code, we have used the write function to write the data that the user in the file gives. Then using the read statement, we read the whole content in the file and printed the data.