C++ 读取多行文件并使用rdbuf()
我有一个多行文件,每行一个字符串C++ 读取多行文件并使用rdbuf(),c++,string,getline,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
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;
}
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
//每个字符串之前要包含的文件
ifstream one(“1.txt”);
//最终输出文件
流式决赛;
final.open(“final.txt”,of stream::app);
//字符串文件
弦线;
ifstream文件(“code.txt”);
while(getline(文件,行))
{
最后, <代码>最终> p>我会改变你的代码>你为什么要使用缓冲区来读取文件?这看起来是个非常糟糕的主意。我在C++参考中找到了这个,我不知道该怎么用,请告诉我,@ tADMAN1.TXT和CDE.TXT的行是一样的,或者只是1行,或者你必须把整个文件放在每行代码之前。大数据块中的文件,不考虑行数,请使用。要逐行复制,请使用。缓冲区对象应单独保留,除非您正在执行一些非常不寻常的操作。在每行@Check之前,请先复制整个文件
while (getline(file,line))
{
final<<one.rdbuf();
final<<line;
one.seekp(0); // <-- add 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;
}