cpp

examples

examples.cpp⚙️
/**
 * File Handling - Examples
 * Compile: g++ -std=c++17 -Wall examples.cpp -o examples
 */

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;

// ============================================================
// SECTION 1: WRITING TEXT FILES
// ============================================================

void demoWriteText() {
    cout << "--- Writing Text Files ---\n" << endl;
    
    // Create and write to file
    ofstream file("output.txt");
    
    if (!file) {
        cerr << "  Cannot create file!" << endl;
        return;
    }
    
    file << "Hello, File!" << endl;
    file << "Line 2 with number: " << 42 << endl;
    file << "Line 3 with float: " << fixed << setprecision(2) << 3.14159 << endl;
    
    file.close();
    cout << "  Created output.txt" << endl;
}

// ============================================================
// SECTION 2: READING TEXT FILES
// ============================================================

void demoReadText() {
    cout << "\n--- Reading Text Files ---\n" << endl;
    
    // Read line by line
    ifstream file("output.txt");
    
    if (!file) {
        cerr << "  Cannot open file!" << endl;
        return;
    }
    
    string line;
    cout << "  Contents:" << endl;
    while (getline(file, line)) {
        cout << "    " << line << endl;
    }
    
    file.close();
}

// ============================================================
// SECTION 3: APPEND TO FILE
// ============================================================

void demoAppend() {
    cout << "\n--- Appending to Files ---\n" << endl;
    
    ofstream file("log.txt", ios::app);
    
    if (!file) {
        cerr << "  Cannot open log file!" << endl;
        return;
    }
    
    file << "Log entry at some time" << endl;
    file.close();
    
    cout << "  Appended to log.txt" << endl;
    
    // Read back
    ifstream readFile("log.txt");
    string line;
    while (getline(readFile, line)) {
        cout << "    " << line << endl;
    }
}

// ============================================================
// SECTION 4: READING FORMATTED DATA
// ============================================================

void demoFormattedRead() {
    cout << "\n--- Reading Formatted Data ---\n" << endl;
    
    // Create data file
    ofstream out("data.txt");
    out << "1 Alice 95.5\n";
    out << "2 Bob 87.3\n";
    out << "3 Charlie 92.1\n";
    out.close();
    
    // Read it back
    ifstream in("data.txt");
    int id;
    string name;
    double score;
    
    cout << "  Student data:" << endl;
    while (in >> id >> name >> score) {
        cout << "    ID: " << id << ", Name: " << name 
             << ", Score: " << score << endl;
    }
}

// ============================================================
// SECTION 5: CSV FILE HANDLING
// ============================================================

void demoCSV() {
    cout << "\n--- CSV File Handling ---\n" << endl;
    
    // Create CSV
    ofstream out("data.csv");
    out << "id,name,score\n";
    out << "1,Alice,95.5\n";
    out << "2,Bob,87.3\n";
    out << "3,Charlie,92.1\n";
    out.close();
    
    // Read CSV
    ifstream in("data.csv");
    string line;
    
    // Skip header
    getline(in, line);
    
    cout << "  CSV contents:" << endl;
    while (getline(in, line)) {
        stringstream ss(line);
        string token;
        vector<string> fields;
        
        while (getline(ss, token, ',')) {
            fields.push_back(token);
        }
        
        cout << "    " << fields[0] << " | " << fields[1] 
             << " | " << fields[2] << endl;
    }
}

// ============================================================
// SECTION 6: BINARY FILES
// ============================================================

struct Record {
    int id;
    double value;
    char name[20];
};

void demoBinary() {
    cout << "\n--- Binary Files ---\n" << endl;
    
    // Write binary
    ofstream out("data.bin", ios::binary);
    
    Record r1 = {1, 3.14, "Record1"};
    Record r2 = {2, 2.71, "Record2"};
    
    out.write(reinterpret_cast<char*>(&r1), sizeof(Record));
    out.write(reinterpret_cast<char*>(&r2), sizeof(Record));
    out.close();
    
    cout << "  Wrote 2 records to data.bin" << endl;
    
    // Read binary
    ifstream in("data.bin", ios::binary);
    Record r;
    
    cout << "  Reading records:" << endl;
    while (in.read(reinterpret_cast<char*>(&r), sizeof(Record))) {
        cout << "    ID: " << r.id << ", Value: " << r.value 
             << ", Name: " << r.name << endl;
    }
}

// ============================================================
// SECTION 7: FILE POSITION
// ============================================================

void demoFilePosition() {
    cout << "\n--- File Position ---\n" << endl;
    
    // Create test file
    ofstream out("position.txt");
    out << "0123456789ABCDEF";
    out.close();
    
    ifstream in("position.txt");
    
    // Read from beginning
    char ch;
    in.get(ch);
    cout << "  Position 0: " << ch << endl;
    
    // Seek to position 10
    in.seekg(10);
    in.get(ch);
    cout << "  Position 10: " << ch << endl;
    
    // Tell current position
    cout << "  Current position: " << in.tellg() << endl;
    
    // Seek from end
    in.seekg(-3, ios::end);
    in.get(ch);
    cout << "  3 from end: " << ch << endl;
    
    // Get file size
    in.seekg(0, ios::end);
    cout << "  File size: " << in.tellg() << " bytes" << endl;
}

// ============================================================
// SECTION 8: ERROR HANDLING
// ============================================================

void demoErrorHandling() {
    cout << "\n--- Error Handling ---\n" << endl;
    
    ifstream file("nonexistent.txt");
    
    if (!file.is_open()) {
        cout << "  File not found (expected)" << endl;
    }
    
    // Check various states
    ifstream file2("output.txt");
    if (file2.good()) {
        cout << "  File is good" << endl;
    }
    
    // Read until EOF
    string line;
    while (getline(file2, line)) { }
    
    if (file2.eof()) {
        cout << "  Reached end of file" << endl;
    }
    
    // Clear error state and reuse
    file2.clear();
    file2.seekg(0);
    getline(file2, line);
    cout << "  After reset, first line: " << line << endl;
}

// ============================================================
// SECTION 9: READ ENTIRE FILE
// ============================================================

void demoReadEntire() {
    cout << "\n--- Read Entire File ---\n" << endl;
    
    // Method 1: stringstream
    ifstream file("output.txt");
    stringstream buffer;
    buffer << file.rdbuf();
    string content = buffer.str();
    
    cout << "  File content (" << content.length() << " chars):" << endl;
    cout << "  " << content.substr(0, 50) << "..." << endl;
}

// ============================================================
// CLEANUP
// ============================================================

void cleanup() {
    cout << "\n--- Cleanup ---" << endl;
    remove("output.txt");
    remove("log.txt");
    remove("data.txt");
    remove("data.csv");
    remove("data.bin");
    remove("position.txt");
    cout << "  Temporary files removed" << endl;
}

// ============================================================
// MAIN
// ============================================================

int main() {
    cout << "╔══════════════════════════════════════╗" << endl;
    cout << "║     FILE HANDLING - EXAMPLES         ║" << endl;
    cout << "╚══════════════════════════════════════╝" << endl;
    
    demoWriteText();
    demoReadText();
    demoAppend();
    demoFormattedRead();
    demoCSV();
    demoBinary();
    demoFilePosition();
    demoErrorHandling();
    demoReadEntire();
    cleanup();
    
    cout << "\n=== Complete ===" << endl;
    return 0;
}
Examples - C++ Tutorial | DeepML