C++ File I/O Lesson

1. File Streams in C++

In C++, files are handled using streams. There are three main classes for file operations:

2. Opening and Closing Files

Files must be opened before performing operations and closed when done using .close().

Writing to a File

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream file("example.txt");
    file << "Hello, World!";
    file.close();
    return 0;
}

Reading from a File

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("example.txt");
    string line;
    while (getline(file, line)) {
        cout << line << endl;
    }
    file.close();
    return 0;
}

3. Appending to a File

ofstream file("example.txt", ios::app);
file << "Appending text.";
file.close();

4. Binary File Operations

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    char name[50];
    int age;
};

int main() {
    Student s = {"John", 20};
    ofstream file("student.dat", ios::binary);
    file.write((char*)&s, sizeof(s));
    file.close();
    return 0;
}


5. Reading from the file.


    #include 
        #include 
        using namespace std;
        
        struct Student {
            char name[50];
            int age;
        };
        
        int main() {
            Student s;
        
            // Read from binary file
            ifstream file("student.dat", ios::binary);
            
            if (file.read((char*)&s, sizeof(s))) {
                cout << "Name: " << s.name << endl;
                cout << "Age: " << s.age << endl;
            } else {
                cout << "Error reading file!" << endl;
            }
        
            file.close();
            return 0;
        }