Writing a binary file in C++

C++Server Side ProgrammingProgramming

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 current 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);


   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 opens successfully, write the binary data using write method.
      Close the file for writing.
   Check if any error occurs.
   Print the data.

Here is a sample example

Example Code

 Live Demo

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));
   if(!wf.good()) {
      cout << "Error occurred at writing 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;


Student’s Details:
Roll No: 1
Name: Ram
Roll No: 2
Name: Shyam
Roll No: 3
Name: Madhu
Published on 03-Apr-2019 06:24:57