使用 fstream 将文件数据从当前位置保存到文件末尾

Saving file data from current position to end of file with fstream

我有一种情况,我循环遍历文件的前 64 行并将每一行保存到一个字符串中。文件的其余部分未知。它可以是单行或多行。 我知道文件开头会有 64 行,但我不知道它们的大小。

如何将文件的其余部分全部保存为字符串?

这是我目前拥有的:

std::ifstream signatureFile(fileName);

for (int i = 0; i < 64; ++i) {
    std::string tempString;
    //read the line
    signatureFile >> tempString;
    //do other processing of string
}
std::string restOfFile;
//save the rest of the file into restOfFile

感谢大家的回复,我就是这样工作的:

std::ifstream signatureFile(fileName);

for (int i = 0; i < 64; ++i) {
    std::string tempString;
    //read the line
    //using getline prevents extra line break when reading the rest of file
    std::getline(signatureFile, tempString);
    //do other processing of string
}

//save the rest of the file into restOfFile
std::string restOfFile{ std::istreambuf_iterator<char>{signatureFile},
        std::istreambuf_iterator<char>{} };
signatureFile.close();

std::string 的构造函数之一是一个模板,它接受两个迭代器作为参数,一个开始迭代器和一个结束迭代器,并根据迭代器定义的序列构造一个字符串。

碰巧 std::istreambuf_iterator 提供了一个合适的输入迭代器来迭代输入流的内容:

std::string restOfFile{std::istreambuf_iterator<char>{signatureFile},
        std::istreambuf_iterator<char>{}};

您可以使用字符串缓冲区。

#include <sstream>

// ...

stringbuf buf;
signatureFile.get(buf);
string restOfFile = buf.str();