×

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:

C and C++ binary files

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:

C and C++ binary files

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.


Related Topics

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

How to Merge Array in C?

Introduction Merging arrays is a common task for many developers but might be difficult for beginners of C programming. Fortunately, our guide will show you how to quickly merge arrays in...

6 minutes read.

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is...

3 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Dangling pointers in C

Dangling pointers in C: A pointer is a variable that stores the memory address of other variables. The pointers may also store the address of other’s memory items. They are...

4 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

Bank management system in C

This is a mini project that is constructed completely using the C language. The bank management system is a beginner friendly project. To construct this user only needs to know...

12 minutes read.

Infix to Postfix program in C

Infix Expression: In infix expression, an operator is placed between the two operands. Example: x + y, here operator + is placed between operands x and y. Postfix Expression: In...

3 minutes read.

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

Recursion in C

Recursion is a programming technique that allows the programmer to call the function within the same function. The function which calls the same function is known as recursive function but a...

1 minute read.

Storage class in C

Storage class in C defines the scope, the visibility, and the lifetime of variables and functions. In other words, storage classes are used to describe the features of variables and...

3 minutes read.

Header files in C

Header files in C In the C programming language, header files are present, which have an extension of ‘.h’, and it consists of macro definitions, declarations, and so on that are...

4 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

getc() function in C

Getc is one of the file handling technique in C. The Getc() is a C library function gets the next character or new characters  from the specific stream and supports...

4 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.