C++——大文件的分段拷贝以及拼接【简单实现】

大文件的分段拷贝以及拼接

需要头文件fstream、iomanip支持以及自定义宏

#define ONE_FILE_SIZE (1024 * 1024 * 10) // 单个文件的最大容量
#define EACH_BLOCK (1024 *  8) // 一次读取的字节数
typedef long long ll;

文件的分段拷贝

void moreFileCopy(const string& fileName)
{
	string copyFileName = fileName;
	ifstream ifs(fileName, ios::binary);
	if (ifs.is_open()) {
		ifs.seekg(0, ios::end);
		ll fileSize = ifs.tellg();
		ifs.seekg(0, ios::beg);
		char buffer[EACH_BLOCK] = { 0 };
		int i = 0;
		string fileName = copyFileName;
		for (int i = 0; !ifs.eof(); ++i) {
			string fileName1 = fileName;
			ofstream ofs(fileName1.insert(fileName.rfind('.'), to_string(i)), ios::binary);
			while (!ifs.eof() && ofs.tellp() < ONE_FILE_SIZE) {
				ifs.read(buffer, sizeof(buffer));
				ll len = ifs.gcount();
				ofs.write(buffer, len);
				ofs.flush();
				ll curSize = ONE_FILE_SIZE * i + ofs.tellp();
				cout << "文件编号[" << i << "]=>" \
					<< fixed << setprecision(2) << "文件总大小: " << ((double)fileSize / 1024 / 1024) \
					<< "MB;当前大小: " << ((double)curSize / 1024 / 1024) << "MB;当前进度: " \
					<< ((double)curSize / fileSize) * 100 << "%" << endl;
			}
			ofs.close();
		}
		ifs.close();
	}
}

效果展示

分段拼接

分段拼接的文件名为去掉0,1,2标号后的文件名。

void moreFileCat(const string& fileName)
{
	ofstream ofs(fileName, ios::binary);
	char buffer[EACH_BLOCK] = { 0 };
	for (int i = 0; true; ++i) {
		string fileName1 = fileName;
		ifstream ifs(fileName1.insert(fileName.rfind('.'), to_string(i)), ios::binary);
		if (!ifs.is_open()) {
			break;
		}
		ifs.seekg(0, ios::end);
		ll fileSize = ifs.tellg();
		ifs.seekg(0, ios::beg);

		while (!ifs.eof()) {
			ifs.read(buffer, sizeof(buffer));
			ll len = ifs.gcount();
			ofs.write(buffer, len);
			ofs.flush();
			ll curSize = ofs.tellp() - (ll)(ONE_FILE_SIZE * i);
			cout << "文件编号[" << i << "]=>" \
				<< fixed << setprecision(2) << "文件总大小: " << ((double)fileSize / 1024 / 1024) \
				<< "MB;当前大小: " << ((double)curSize / 1024 / 1024) << "MB;当前进度: " \
				<< ((double)curSize / fileSize) * 100 << "%" << endl;
		}
		ifs.close();
	}
	ofs.close();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值