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

标签 c++ file fstream ifstream

我有这样一种情况,我循环遍历文件的前 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/

相关文章:

java - 如何在编程语言中生成一些长度固定为 r 的同分布伪随机 vector ?

c++ - 具有单个参数的模糊构造函数 : initializer_list and int

c++ - 在 vector 中使用具有 const 数据成员的类

php - 文字空白字符导致模式失败(有时)

c++ - 在 C++ 中使用 THIS 指针将对象写入文件

c++ - 来自自定义类的对象 vector

C - 使用 strtok() 将文件从命令行管道传输到 C 程序

c# - 目录的 GetTempFileName 函数?

c++ - 未创建具有 fstream 对象的文件对象

c++ - 在 std::ofstream (c++) 中复制 std::cout