C語言簡單實現檔案分塊
阿新 • • 發佈:2018-11-08
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值是否相同。