Skip to content
C++

File IO

File read and write operations.

By EZ4Code Team
iofile

Code

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main() {
    // Write file
    std::ofstream out("data.txt");
    out << "Hello World\n";
    out << 42 << " " << 3.14 << "\n";
    out.close();

    // Read file (line by line)
    std::ifstream in("data.txt");
    std::string line;
    while (std::getline(in, line)) {
        std::cout << "Line: " << line << "\n";
    }
    in.close();

    // Read file (word by word)
    std::ifstream in2("data.txt");
    std::string word;
    while (in2 >> word) {
        std::cout << "Word: " << word << "\n";
    }

    // Binary read/write
    std::ofstream bin("data.bin", std::ios::binary);
    int nums[] = {1, 2, 3, 4, 5};
    bin.write(reinterpret_cast<char*>(nums), sizeof(nums));
    bin.close();

    std::ifstream bin2("data.bin", std::ios::binary);
    int read_nums[5];
    bin2.read(reinterpret_cast<char*>(read_nums), sizeof(read_nums));

    // stringstream
    std::stringstream ss;
    ss << "value=" << 42;
    std::string s = ss.str();

    // Append mode
    std::ofstream app("log.txt", std::ios::app);
    app << "new entry\n";

    return 0;
}

Explanation

ofstream writes files; ifstream reads files; stringstream is a string stream; supports text and binary modes.

More C++ Snippets