Search code examples
c++memory-managementfile-ioifstreamgetline

Read from a file into a single block of memory using C++


I have an ASCII file which contains only a single line. I would like to load the whole line into a std::string object. While doing this, I want the whole char array to be placed into a single contiguous memory block. What is the best way of doing this?

Currently, I read the whole file as follows:

std::ifstream t(fname);
std::string pstr;

t.seekg(0, std::ios::end);
pstr.reserve(t.tellg());
t.seekg(0, std::ios::beg);

pstr.assign(std::istreambuf_iterator<char>(t),
            std::istreambuf_iterator<char>());

If I do in the following way, will the string be placed in a single memory block, too?

std::ifstream t(fname);
std::string pstr;
std::getline(t, pstr);

If both ways gives the desired feature, which one should be preferred?


Solution

  • If I do in the following way, will the string be placed in a single memory block, too?

    Yes, both methods will do that.

    If both ways gives the desired feature, which one should be preferred?

    The 1st one should be preferred to avoid recurring (re-)allocation of the targeted std::string. Using a std::back_inserter would be more idiomatic though.