我有这样一种情况,我循环遍历文件的前 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>{}};
关于c++ - 使用 fstream 将文件数据从当前位置保存到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42204700/