Writing
To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is currently at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data.
If any error has occurred during writing in the file, the stream is placed in an error state.
Syntax of write method
ostream& write(const char*, int);
Reading
To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then.
gcount() can be used to count the number of characters has already read. Then clear() can be used to reset the stream to a usable state.
Syntax of read method
ifstream& write(const char*, int);
Algorithm
Begin Create a structure Student to declare variables. Open binary file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read. Check if any error occurs in file opening. If file open successfully, read the binary data file using read method. Close the file for reading. Check if any error occurs. Print the data. End.
Example Code
#include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; 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_no = 1; wstu[0].name = "Ram"; wstu[1].roll_no = 2; wstu[1].name = "Shyam"; wstu[2].roll_no = 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_no << endl; cout << "Name: " << wstu[i].name << endl; cout << endl; } return 0; }
Output
Student’s Details: Roll No: 1 Name: Ram Roll No: 2 Name: Shyam Roll No: 3 Name: Madhu