[英]Read multiline file and using rdbuf()
I've a multiline file, every line a string. 我有一个多行文件,每行一个字符串。
Example of code.txt
: 示例
code.txt
:
AAAAA
BB33A
C544W
I have to put some code contained in another file before every string. 我必须在每个字符串之前放入另一个文件中包含的一些代码。 I'm using this:
我正在使用这个:
#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;
}
}
Now, this doesn't work, it works only for the first line of code.txt
. 现在,这行不通,仅适用于
code.txt
的第一行。 What is wrong? 怎么了?
final<<one.rdbuf()
works for only the first line because once you stream out the rdbuf
the first time, its read pointer is sitting at the end of the 1.txt
file data. final<<one.rdbuf()
仅适用于第一行,因为一旦您第一次将rdbuf
流出,其读指针就位于1.txt
文件数据的末尾。 There is no data left for it to read on subsequent streaming. 没有剩余数据供后续流式传输读取。 You would have to reset the
one
stream back to the beginning of its data on each loop iteration, eg: 您必须在每次循环迭代中将
one
流重置回其数据的开头,例如:
while (getline(file,line))
{
final<<one.rdbuf();
final<<line;
one.seekp(0); // <-- add this
}
Otherwise, do as @Check suggests. 否则,请按照@Check的建议进行操作。 Read the content of the
1.txt
file into memory one time, and then stream that out on each loop iteration, instead of re-reading the file on each iteration. 一次将
1.txt
文件的内容读入内存,然后在每次循环迭代中将其流式传输出去,而不是在每次迭代时重新读取该文件。
I would change your final<<one.rdbuf();
我会更改您的
final<<one.rdbuf();
. 。 You can use this:
您可以使用此:
//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;
}
Maybe you want to check this https://stackoverflow.com/a/8737787/3065110 也许您想检查一下这个https://stackoverflow.com/a/8737787/3065110
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.