An easy way to read a whole text file with standard c++ and stl

· Read in about 1 min · (109 Words)
C++

Have you ever wondered what would be the easiest way to read a whole text file in a string? There are many ways to skin that cat, but here is one I find myself using the following code:

#include <fstream>
#include <string>

int main()
{
    std::string str; // Will hold the contents of the file

    std::ifstream fileStream("test.txt");

    // Figure out how big is the file and reserve space
    fileStream.seekg(0, std::ios::end);
    str.reserve(fileStream.tellg());
    fileStream.seekg(0, std::ios::beg);

    // Read it
    str.assign((std::istreambuf_iterator<char>(fileStream)), std::istreambuf_iterator<char>());

    return 0;
}

Easy and very useful for small text files, but I wouldn’t use it for larger files. You are probably better off reading a line at a time :-).