Let’s write a comprehensive C++ code that:

  1. Demonstrates all major file modes (ios::in, out, app, trunc, binary).
  2. Uses all important file functions: open(), close(), write, read, seekg/seekp, tellg/tellp, etc.
  3. Includes both text and binary I/O.
  4. Shows Python equivalents for direct comparison.

Task:

We’ll:

  1. Write to a file.
  2. Append to the same file.
  3. Read from it.
  4. Use seek/tell.
  5. Save and read binary data.

C++ Code (Complete Example)

#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;
}