使用 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();
相关文章:
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 从函数角度看ID到文件路径的内部与外部映射
- 如何在特定位置追加 json 文件
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 如何使用 fprintf 将连续的 512 字节保存到文件中
- 看不到文件'SDL2.lib'
- 将字符串存储到文件下一行的变量中
- 将类型保存到文件
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- C++ 生成文件未检测到 .h 文件中的更改
- 如何存储 unicode 字符并将其输出到文件?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 提取字符后返回到文件中的特定位置
- 使用 fstream 将文件数据从当前位置保存到文件末尾
- 在 C++ 中,从文件找到一行后从该位置复制到该文件的末尾
- 如何将sql数据库文件从系统位置复制到另一个位置
- 将文件从 SDCARD 位置复制到 Android 中 c 语言的另一个位置
- 在c++中,将数据插入到文件中的特定位置而不进行覆盖
- 将文件内容从特定位置获取到另一个特定位置
- 图像处理-以最快的方式跳到文件中的位置(C/C++)