【C++/文件读写】合并两文件

要求

编写一程序,将两个文件合并成一个文件

代码

#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();
  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值