1. Streams and File I/O

In C++, streams represent the flow of data in sequence. There are two main types of I/O operations:

Standard Stream Objects

File Stream Classes

C++ provides three main classes for file operations:

  1. ifstream: Derived from istream, used for reading from files
  2. ofstream: Derived from ostream, used for writing to files
  3. fstream: Derived from iostream, used for both reading and writing
#include <fstream>
#include <iostream>
using namespace std;

int main() {
    // Writing to a file
    ofstream outFile("data.txt");
    if(outFile.is_open()) {
        outFile << "Hello, this is sample text." << endl;
        outFile << 100 << " " << 3.14 << endl;
        outFile.close();
    }

    // Reading from a file
    ifstream inFile("data.txt");
    if(inFile.is_open()) {
        string line;
        while(getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }

    return 0;
}

File Types

  1. Text Files:
  2. Binary Files:

File Modes