使用 C++ 从文件读取到单个内存块

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

我有一个只包含一行的 ASCII 文件。我想将整行加载到 std::string 对象中。在执行此操作时,我希望将整个 char 数组放入一个连续的内存块中。这样做的最佳方法是什么?

目前,我阅读了整个文件如下:

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>());

如果我按照下面的方式做,字符串也会被放在一个内存块中吗?

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

如果两种方式都能提供所需的功能,应该首选哪一种?

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

是的,两种方法都可以。

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

应该首选第一个,以避免重复(重新)分配目标 std::string。不过,使用 std::back_inserter 会更加地道。