Read/Write File in C++

input/output library

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';
}
Written on September 25, 2020, Last update on June 27, 2021
c++ file io-stream