我有一个多行文件,每一行都是一个字符串。
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
的第一行。有什么问题?
答案 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;
}
答案 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
文件的内容一次读入内存,然后在每次循环迭代中将其流出,而不是在每次迭代时重新读取文件。