要求
编写一程序,将两个文件合并成一个文件
代码
#include <iostream>
#include "fstream"
using namespace std;
/**
* 2编写一程序,将两个文件合并成一个文件。
*/
#define FILEPATH1 "file1.txt"
#define FILEPATH2 "file2.txt"
#define FILEPATH3 "fileout.txt"
void CombileFiles()
{
//2.1首先读取两个文件内容放在内存中
//申请文件句柄
ifstream fin1, fin2;
ofstream fout;
fin1.open(FILEPATH1, ios::in);
if (fin1.fail())
{
cout << "empty file 1" << endl;
fin1.close();
return;
}
fin2.open(FILEPATH2, ios::in);
if (fin2.fail())
{
cout << "empty file 2" << endl;
fin2.close();
return;
}
fout.open(FILEPATH3, ios::out);
if (fout.fail())
{
cout << "empty file out" << endl;
fout.close();
return;
}
char tmpBuf1[1024];
char tmpBuf2[1024];
while (!fin1.eof())
{
fin1.getline(tmpBuf1, 1024);
cout << tmpBuf1 << endl;
fout << tmpBuf1 << endl;
}
while (!fin2.eof())
{
fin2.getline(tmpBuf2, 1024);
cout << tmpBuf2 << endl;
fout << tmpBuf2 << endl;
}
cout << "文件合并完成!" << endl;
fin1.close();
fin2.close();
fout.close();
}
int main()
{
CombileFiles();
cout << "hello world!" << endl;
system("pause");
return 0;
}
注意
写文件用 ofstream
ofstream fout("test.txt");
fout << "this is for testing..." << endl;
fout.close();
读文件用 ifstream
ifstream fin("test.txt");
char buf[1024] = {};
while(!fin.eof())
{
fin.getline(buf, 1024); //按行来读
cout << buf << endl; //打印信息
}
fout.close();