#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int getFileSize(char *path)
{
FILE *pfr = fopen(path, "rb");
if (pfr == NULL)
{
printf("文件打开失败!\n");
return;
}
else
{
int sum = 0;
int ch;
while ((ch = fgetc(pfr)) != EOF)
{
sum++;
}
return sum;
}
}
void segmentationFile(char *path, int num)
{
char name[1024] = "I:\\fudan\\ascii.gif"; //要分割的文件名
char **ppath;
//分割文件名
ppath = malloc(sizeof(char *)*num);
for (int i = 0; i < num; i++)
{
ppath[i] = malloc(sizeof(char)* 1024);
sprintf(ppath[i], "I:\\fudan\\a%d.gif", i + 1); //分割后的每个文件名
//printf("%s\n", ppath[i]);
}
FILE *pfr = fopen(path, "rb");
if (pfr == NULL)
{
printf("文件打开失败!\n");
return;
}
int size = getFileSize(path);
if (size % num == 0) //如果文件能被整除
{
for (int i = 0; i < num; i++)
{
FILE *pfw = fopen(ppath[i], "wb");
for (int j = 0; j < size / num; j++)
{
//写入到分割的文件中
fputc(fgetc(pfr), pfw);
}
fclose(pfw);
}
fclose(pfr);
}
else //文件不能被整除
{
for (int i = 0; i < (num - 1); i++) //整数部分
{
FILE *pfw = fopen(ppath[i], "wb");
for (int j = 0; j < size / (num - 1); j++)
{
fputc(fgetc(pfr), pfw);
}
fclose(pfw); //每次都要关闭相应打开的文件
}
//不足的部分
FILE *pfw = fopen(ppath[num - 1], "wb");
for (int i = 0; i < size %num; i++)
{
fputc(fgetc(pfr), pfw);
}
fclose(pfw);
}
fclose(pfr);
}
void mergeFile(char *path,int num)
{
char name[1024] = "I:\\fudan\\ascii.gif";
char **ppath;
//获取分割后的文件名
FILE *pfw = fopen(path, "wb");
ppath = malloc(sizeof(char *) * num);
for (int i = 0; i < num; i++)
{
ppath[i] = malloc(sizeof(char)* 1024);
sprintf(ppath[i], "I:\\fudan\\a%d.gif",i+1);
}
for (int i = 0; i < num; i++)
{
int length = getFileSize(ppath[i]); //得到每个文件的大小。
FILE *pfr = fopen(ppath[i], "rb");
for (int j = 0; j < length; j++) //把每个文件都写入到一个文件中。
{
fputc(fgetc(pfr), pfw);
}
fclose(pfr);
}
fclose(pfw);
}
void main()
{
//分割文件
segmentationFile("I:\\fudan\\ascii.gif", 10);
//合并文件
mergeFile("I:\\fudan\\ai.gif", 10);
system("pause");
}