Let’s write a comprehensive C++ code that:
We’ll:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string filename = "demo.txt";
// 1. Write to a file (ios::out | ios::trunc)
{
ofstream outFile(filename, ios::out | ios::trunc);
if (!outFile) {
cerr << "Failed to open file for writing.\\n";
return 1;
}
outFile << "Line 1\\nLine 2\\n";
outFile.close();
}
// 2. Append more content (ios::app)
{
ofstream appFile(filename, ios::out | ios::app);
appFile << "Line 3 (appended)\\n";
appFile.close();
}
// 3. Read file content (ios::in)
{
ifstream inFile(filename, ios::in);
string line;
cout << "Reading file:\\n";
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
// 4. Seek & tellg
{
ifstream inFile(filename, ios::in);
inFile.seekg(0, ios::end);
streampos size = inFile.tellg();
cout << "File size: " << size << " bytes\\n";
inFile.seekg(0, ios::beg);
inFile.close();
}
// 5. Binary Write
{
ofstream binOut("demo.bin", ios::binary);
vector<int> data = {10, 20, 30, 40};
binOut.write(reinterpret_cast<char*>(data.data()), data.size() * sizeof(int));
binOut.close();
}
// 6. Binary Read
{
ifstream binIn("demo.bin", ios::binary);
vector<int> readData(4);
binIn.read(reinterpret_cast<char*>(readData.data()), readData.size() * sizeof(int));
cout << "Binary Read: ";
for (int val : readData) cout << val << " ";
cout << endl;
binIn.close();
}
return 0;
}