×

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

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

C Math Library

C Math Library The <math.h> header defines various mathematical functions and one macro. Many functions are available in this library to take double as an argument and then return double as...

4 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

Memory layout in C

Memory layout in C The C language is designed so that it becomes easier for a programmer to decide the amount of memory they want to use in a program. C program...

4 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

gets() function in C

gets() is a pre-define or built-in function present in the stdio.h header file. stdio stands for standard input and output. gets() function is used to read a stream and store...

4 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.