
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Writing a Binary File in C++
To write a binary file in C++, use write method like fwrite()/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
Following is the basic syntax of writing a binary file in C++:
ostream& write(const char*, int);
Algorithm
Following is the algorithm is as follows:
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 opens successfully, write the binary data using write method. Close the file for writing. Check if any error occurs. Print the data. End.
C++ Program to Write a Binary File
This program defines a "Student" structure and stores 3 student records (roll number and name). It writes these records into a binary file (student.dat) using write(), and then prints the same data to the console. It uses a fixed-size character array as char name[50] to store and write names as raw binary:
#include<iostream> #include<fstream> #include<cstring> using namespace std; // Define structure for Student struct Student { int roll_no; char name[50]; // Fixed-size character array for name }; int main() { // Open binary file for writing ofstream wf("student.dat", ios::out | ios::binary); if (!wf) { cout<<"Cannot open file!"<<endl; return 1; } // Initialize student data Student wstu[3]; wstu[0].roll_no = 1; strcpy(wstu[0].name, "Revathi"); wstu[1].roll_no = 2; strcpy(wstu[1].name, "Vivek"); wstu[2].roll_no = 3; strcpy(wstu[2].name, "Tapas"); // Write each student record to the binary file for (int i = 0; i<3; i++) { wf.write(reinterpret_cast<char*>(&wstu[i]), sizeof(Student)); } wf.close(); // Close file after writing // Check if write operation was successful if (!wf.good()) { cout<<"Error occurred at writing time!"<<endl; return 1; } // Display student data cout<<"Student's Details:\n"; for (int i = 0; i<3; i++) { cout<<"Roll No: "<<wstu[i].roll_no<<endl; cout<<"Name: "<<wstu[i].name<<endl; } return 0; }
Following is the output to the above program:
Student's Details: Roll No: 1 Name: Revathi Roll No: 2 Name: Vivek Roll No: 3 Name: Tapas