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

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

本文关键字:位置 存到文件 fstream 文件 数据 使用      更新时间:2023-10-16

我遇到这样一种情况:我遍历文件的前 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();