0% found this document useful (0 votes)
2 views2 pages

C++ Binary File Read/Write Example

The document contains a C++ program that writes user-inputted strings to a binary file named 'data.bin' and then reads from that file. It uses fstream for file operations and handles both writing and reading in binary mode. The program terminates input when the user types 'End' and ensures proper file handling with error checks.

Uploaded by

thanusha0711
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

C++ Binary File Read/Write Example

The document contains a C++ program that writes user-inputted strings to a binary file named 'data.bin' and then reads from that file. It uses fstream for file operations and handles both writing and reading in binary mode. The program terminates input when the user types 'End' and ensures proper file handling with error checks.

Uploaded by

thanusha0711
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q8. Write a C++ program to write and read time in/from binary file using fstream?

Code:

#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
int main() {
ofstream outFile("[Link]", ios::out | ios::binary | ios::trunc);
string InputLine;
const int BUFFER_SIZE = 100;
char bu er[BUFFER_SIZE];
if (!outFile)
{
cerr << "Cannot open file for writing!" << endl;
return 1;
}
cout << "Input :" << endl;
while(true)
{
getline(cin, InputLine);
if(InputLine == "End")
break;
strncpy(bu er, InputLine.c_str(), BUFFER_SIZE);
bu er[BUFFER_SIZE - 1] = '\0';
[Link](bu er, BUFFER_SIZE);
}
[Link]();
cout << "Data written successfully." << endl;
ifstream inFile("[Link]", ios::in | ios::binary);
if (!inFile)
{
cerr << "Cannot open file for reading!" << endl;
return 1;
}
while ([Link](bu er, BUFFER_SIZE))
{
cout << bu er << endl;
}
[Link]();
return 0;
}

You might also like