Reading and writing binary file in C/C++ (2024)

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: 1Name: RamRoll No: 2Name: ShyamRoll No: 3Name: Madhu

Read Also: C++ Files and Streams

Kickstart Your Career

Get certified by completing the course

Get Started

Reading and writing binary file in C/C++ (2)

Advertisem*nts

Reading and writing binary file in C/C++ (2024)
Top Articles
Aggregation
What is Data Aggregation?
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated:

Views: 5848

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.