当前位置:编程学习 > C/C++ >>

文件分割工具

#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	string path;
	cout<<"请输入要分隔的文件路径:";
	cin>>path;
	string block;
	cout<<"请输入每块的文件大小(1G/1M/1K/1B):";
	cin>>block;
	const int block_size=33554432;
	unsigned __int64 size;
	int ubound=block.size()-1;
	sscanf(block.substr(0,ubound).c_str(),"%I64d",&size);
	switch(block[ubound])
	{
	case 'G':
		{
			size <<=30;
			break;
		}
	case 'M':
		{
			size <<=20;
			break;
		}
	case 'K':
		{
			size <<=10;
			break;
		}
	default:
		{
			break;
		}
	}
	ifstream in(path.c_str(),ios::binary);
	if(!in)
	{
		cout<<"打开文件失败,请重新运行!"<<endl;
		return -1;
	}
	int count=0;
	double sum=0;
	char *buf=new char[block_size];
	ofstream out((path+".bat").c_str());
	out<<"@echo off"<<endl;
	out<<"echo -----------------------------------------------------"<<endl;
	out<<"echo -               欢迎使用文件分割工具                -"<<endl;
	out<<"echo -                                                   -"<<endl;
	out<<"echo -                                                   -"<<endl;
	out<<"echo -----------------------------------------------------"<<endl;
	for(int i=1;i>0;i++,count++)
	{
		itoa(i,buf,10);
		string fullname=path+".part"+buf;
		cout<<"正在生成"<<fullname<<endl;
		ofstream fout(fullname.c_str(),ios::binary | ios::trunc);
		unsigned __int64 current_size=size;
		while(current_size>0)
		{
			if(current_size>=block_size)
			{
				in.read(buf,block_size);
			}
			else
			{
				in.read(buf,current_size);
			}
			if(in.gcount()==0)
			{
				i=-1;
				break;
			}
			current_size -=in.gcount();
			sum +=in.gcount();
			fout.write(buf,in.gcount());
		}
		fout.close();
	}
	out<<"echo 本批处理文件共分成 "<<count<<" 个子文件,共 ";
	if(sum>=1000000000)
	{
		out<<fixed<<setprecision(2)<<sum/1073741824<<" G";
	}
	else if(sum>=1000000)
	{
		out<<fixed<<setprecision(2)<<sum/1048576<<" M";
	}
	else if(sum>=1000)
	{
		out<<fixed<<setprecision(2)<<sum/1024<<" K";
	}
	else
	{
		out<<sum<<" B";
	}
	out<<endl;
	out<<"echo 请确认: 1、子文件的个数是否相符并放在当前目录下"<<endl;
	out<<"echo         2、可用剩余空间是否足够"<<endl;
	out<<"pause"<<endl;
	out<<"echo 开始合并文件,合并过程中请勿关闭,合并时间长短与文件的大小有关"<<endl;
	out<<"echo 合并结束后会自动关闭当前窗口"<<endl;
	out<<"echo 请稍后... "<<endl;
	out<<"copy /b ";
	int pos=path.find_last_of('\\');
	string filename=path.substr(pos+1);
	for(i=0;i<count;i++)
	{
		out<<filename<<".part"<<i+1;
		if(i<count-1)
		{
			out<<'+';
		}
	}
	out<<' '<<filename<<endl;
	out.close();
	delete [] buf;
	in.close();
	cout<<"文件分割成功!"<<endl;
	system("pause");
	return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,