#include<stdio.h>
#include<stdlib.h>#define NAME_LENGTH 100
#define BUFFER_SIZE 1024
#define MIN_SIZE 1
#define MAX_SIZE 1024void 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 * 1MBfor(int j=0;j<1024 && !feof(file);j++){//read 1MBint 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);//1KBfwrite(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 output file>>\n");gets(filename); printf("Wait...\n");FileMerge(filename);printf("Finish.\n");}printf("Continue selecting function\n>>");}return 0;
}