Read/Write File in C++

input/output library - ChatGPT

Return content of stream as a string

std::string load_stream(std::istream& src)
{
    std::ostringstream buf;
    buf << src.rdbuf();
    return buf.str();
}

std::ifstream in("input/test1.txt");
cerr << load_stream(in);

Write file binary / text

{   // scoped, so that ostrm desctructor will close file by the end
    std::ofstream ostrm("Test.b", std::ios::binary);
    double d = 3.14;
    // binary output
    ostrm.write(reinterpret_cast<char*>(&d), sizeof d); 
    // text output
    ostrm << 123 << "abc" << '\n';
}

Read some data by lines

#include <sstream>  // For std::stringstream

while (std::getline(inputFile, line)) {
    std::stringstream ss(line);
    char comma;  // To discard the comma
    ss >> a >> comma >> b;
    pairs.emplace_back(a, b);
}
Written on September 25, 2020, Last update on December 1, 2024
c++ file io-stream