下面是切割文件和合并文件的代码,是我用来熟悉文件操作函数时写的一些东西,大有完善的余地,与大家分享,听取大家指教。程序在UNIX_AIX下调试通过。
/***************************
mycut.c
文件切割程序
用于将文件切割成1024字节大小的小文件
***************************/
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#define SIZE 1024
#define MAX 1048576*5
main(int argc, char **argv)
{
char buffer[SIZE],c;
FILE *source, *target;
struct stat sbuf;
int count = 0, n = 0;
char flag = '0';
char mycount[10];
char parts[10];
char mysign[20];
if(argc != 2)
{
fprintf(stderr, "Usage: source--file\n", *argv);
exit(1);
}
if((source = fopen(argv[1],"r")) == NULL)
{
perror(argv[1]);
exit(1);
}
stat(argv[1], &sbuf);
if(sbuf.st_size > MAX)
{
printf("the file is too big \n");
exit(0);
}
/*计算文件的块数*/
count = sbuf.st_size / SIZE + 1;
memset(mysign, 0, 10);
printf("%d\n", count);
/*记录文件个数*/
target = fopen("thecount","w");
sprintf(mysign, "%d", count);
fputs(mysign, target);
fclose(target);
/*记录文件名*/
target = fopen("thefilename","w");
fputs(argv[1], target);
fclose(target);
for(flag=0; flag<count; flag++)
{
sprintf(mysign,"%d",flag);
printf("%s",mysign);
target = fopen(mysign, "w");
n = fread(buffer, sizeof(char), SIZE, source);
fwrite(buffer, sizeof(char), n, target);
fclose(target);
}
fclose(source);
exit(0);
}
/***************************
mycomb.c
文件合并程序
用于将用上面程序切割的小文件合并复原
***************************/
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#define SIZE 1024
#define MAX 1048576*5
main(int argc, char **argv)
{
char buffer[SIZE],c;
FILE *source, *target;
struct stat sbuf;
int count = 0, n = 0;
char flag = '0';
char mycount[10];
char filename[20];
char mysign[10];
/*获得文件块数信息*/
if((source = fopen("thecount","r")) == NULL)
{
printf("some thing is wrong\n");
exit(1);
}
memset(mycount, 0, 10);
fgets(mycount,10,source );
fclose(source);
remove("thecount");
count = atoi(mycount);
/*获得文件名信息*/
if((source = fopen("thefilename","r")) == NULL)
{
printf("some thing is wrong\n");
exit(1);
}
memset(filename, 0, 20);
fgets(filename,10,source );
fclose(source);
remove("thefilename");
target = fopen(filename,"a");
memset(mysign, 0 ,10);
/*文件合并*/
for(flag=0; flag<count; flag++)
{
sprintf(mysign,"%d",flag);
printf("%s",mysign);
source = fopen(mysign, "r");
n = fread(buffer, sizeof(char), SIZE, source);
fwrite(buffer, sizeof(char), n, target);
fclose(source);
remove(mysign);
}
fclose(target);
exit(0);
}
本文地址:http://com.8s8s.com/it/it29031.htm