C语言简单实现文件分块

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wingrez/article/details/83029479

C语言简单实现文件分块

模块1:分割文件
指定目标输入文件(文件名或文件路径)和分割尺寸,要求分割尺寸(单位:MB)为正整数,且范围在[MIN_SIZE, MAX_SIZE]。
分割后产生块文件,命名格式为“part_”+编号。

模块2:合并文件
指定目标输出文件(文件名或文件路径)。
顺序合并块文件。

#include<stdio.h>
#include<stdlib.h>

#define NAME_LENGTH 100
#define BUFFER_SIZE 1024
#define MIN_SIZE 1
#define MAX_SIZE 10240

void FileSplit(FILE *file,int size){
	if(file==NULL){
		printf("Unable to read file.\n");
		exit(-1);
	}
	if(size<MIN_SIZE || size>MAX_SIZE){
		printf("The size must be a positive integer(%dMB to %dMB).\n",MIN_SIZE,MAX_SIZE);
		exit(-3);
	}
	char partname[NAME_LENGTH];
	int buffer[BUFFER_SIZE]; 
	int num=0;
	while(!feof(file)){
		sprintf(partname,"part_%d",++num);
		FILE *fout=fopen(partname,"wb");
		if(file==NULL){
			printf("Unable to create file.\n");
			exit(-2);
		}
		for(int i=0;i<size && !feof(file);i++){//read size * 1MB
			for(int j=0;j<1024 && !feof(file);j++){//read 1MB
				int cnt=fread(buffer,1,1024,file);//read 1KB, may less than 1KB.
				fwrite(buffer,1,cnt,fout);
			}
		}
		fclose(fout);
	}
}

void FileMerge(char *filename){
	char partname[NAME_LENGTH];
	int buffer[BUFFER_SIZE]; 
	int num=0;
	FILE *fin,*fout=fopen(filename,"wb");
	if(fout==NULL){
		printf("Unable to create file.\n");
		exit(-2);
	} 
	while(sprintf(partname,"part_%d",++num) && (fin=fopen(partname,"rb"))!=NULL){
		while(!feof(fin)){
			int cnt=fread(buffer,1,1024,fin);//1KB
			fwrite(buffer,1,cnt,fout);
		}
		fclose(fin);
	}
	fclose(fout);
}

int main(){
	printf("Selection function:\n1.FileSplit\n2.FileMarge\n0.quit\n>>");
	int choose=0;
	while(scanf("%d",&choose) && choose){
		while(getchar()!='\n') continue;
		char filename[NAME_LENGTH];
		if(choose==1){
			printf("Please enter the name of the target file>>\n");
			gets(filename); 
			FILE *fin=fopen(filename,"rb");
			printf("Please enter the size(MB) of each block>>\n");
			int size=0;
			scanf("%d",&size);
			printf("Wait...\n");
			FileSplit(fin,size);
			fclose(fin);
			printf("Finish.\n");
		}
		else if(choose==2){
			printf("Please enter the name of the target file>>\n");
			gets(filename); 
			printf("Wait...\n");
			FileMerge(filename);
			printf("Finish.\n");
		}
		printf("Continue selecting function\n>>");
	}
	return 0;
}

建议:检验原文件和合并文件的MD5值是否相同。

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/83029479