读取多行文件并使用rdbuf()

时间:2017-08-31 18:07:32

标签: c++ string getline

我有一个多行文件,每一行都是一个字符串。

code.txt的示例:

AAAAA
BB33A
C544W

我必须在每个字符串之前将一些代码包含在另一个文件中。我用这个:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    //the file to include before every string
    ifstream one("1.txt");

    //final output file
    ofstream final;
    final.open ("final.txt", ofstream::app);

    //string file
    string line;
    ifstream file("code.txt");

    while (getline(file,line))
    {
       final<<one.rdbuf();
       final<<line;
    }
}

现在,这不起作用,它仅适用于code.txt的第一行。有什么问题?

2 个答案:

答案 0 :(得分:1)

我会改变你的final<<one.rdbuf();。 你可以用这个:

//the file to include before every string
ifstream one("1.txt");

std::string first;
if (one.is_open())
{
    // file length and reserve the memory.
    one.seekg(0, std::ios::end);
    first.reserve(static_cast<unsigned int>(one.tellg()));
    one.seekg(0, std::ios::beg);

    first.assign((std::istreambuf_iterator<char>(one)),
                 (std::istreambuf_iterator<char>()));

    one.close();
}

//final output file
ofstream final;
final.open ("final.txt", ofstream::app);

//string file
string line;
ifstream file("code.txt");

while (getline(file,line))
{
    final<<first;
   final<<line;
}

也许您想查看https://stackoverflow.com/a/8737787/3065110

答案 1 :(得分:0)

final<<one.rdbuf()仅适用于第一行,因为第一次流出rdbuf后,其读指针位于1.txt文件数据的末尾。在后续流媒体上没有剩余数据可供阅读。您必须在每次循环迭代时将one流重置回其数据的开头,例如:

while (getline(file,line))
{
   final<<one.rdbuf();
   final<<line;
   one.seekp(0); // <-- add this
}

否则,请按@Check建议。将1.txt文件的内容一次读入内存,然后在每次循环迭代中将其流出,而不是在每次迭代时重新读取文件。

相关问题