c语言-文件操作(3)
文件分割和合并
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
//文件切割与合并
static char path[128] = "F:\\project\\csharp\\qiufeng.console\\Debug"; //文件路径
char **paths; //存放分割文件的文件名
int getFileSize(char *path)
{
FILE *pReader = fopen(path, "rb");
if (pReader == NULL)
{
return -1;
}
else
{
fseek(pReader, 0, SEEK_END);
int len = ftell(pReader);
fclose(pReader);
return len;
}
}
int splitFile(char *path, int num) //分割文件
{
paths = malloc(sizeof(char *)*num);
for (int i = 0; i < num; i++)
{
paths[i] = malloc(sizeof(char) * 128);
sprintf(paths[i], "%s\\1_%d.pdf", path, i + 1);
printf("%s\n", paths[i]);
}
char readFilePath[128];
sprintf(readFilePath, "%s\\%s", path, "1.pdf"); //格式化字符,将文件名称和路径合并
FILE *pReader = fopen(readFilePath, "rb");
if (pReader == NULL)
{
printf("打开文件失败!\n");
return 0;
}
else
{
int fileSize = getFileSize(readFilePath);
if (fileSize%num == 0) //能整除的情况
{
for (int i = 0; i < num; i++)
{
FILE *pWriter = fopen(paths[i], "wb");
for (int j = 0; j < fileSize / num; j++)
{
fputc(fgetc(pReader), pWriter);
}
fclose(pWriter);
}
}
else //不能整除的情况
{
for (int i = 0; i < num - 1; i++)
{
FILE *pWriter = fopen(paths[i], "wb");
for (int i = 0; i < fileSize / (num - 1); i++)
{
fputc(fgetc(pReader), pWriter);
}
fclose(pWriter);
}
//不能整除的剩余部分
{
FILE *pWriter = fopen(paths[num - 1], "wb");
for (size_t i = 0; i < fileSize%num; i++)
{
fputc(fgetc(pReader), pWriter);
}
fclose(pWriter);
}
}
fclose(pReader);
}
return 1;
}
int combineFile(char *path, int num) //合并文件
{
paths = malloc(sizeof(char *)*num);
char newFilePath[128];
sprintf(newFilePath, "%s\\%s", path, "newfile.pdf");
FILE *pWriter = fopen(newFilePath, "wb");
if (pWriter == NULL)
{
printf("打开文件失败!");
return 0;
}
for (int i = 0; i < num; i++)
{
paths[i] = malloc(sizeof(char) * 128);
sprintf(paths[i], "%s\\1_%d.pdf", path, i + 1);
printf("%s\n", paths[i]);
FILE *pReader = fopen(paths[i], "rb");
while (!feof(pReader))
{
fputc(fgetc(pReader), pWriter);
}
fclose(pReader);
}
fclose(pWriter);
return 1;
}
int main(int argc, char *argv[])
{
int num;
scanf("%d", &num);
int splitResult = splitFile(path, num);
if (splitResult)
{
printf("文件分割完成!\n");
}
else
{
printf("文件分割失败!\n");
}
int combineResult = combineFile(path, num);
if (combineResult)
{
printf("文件合并完成!\n");
}
else
{
printf("文件合并失败!\n");
}
system("pause");
return 0;
}
效果
运行效果

生成效果

秋风
2016-07-10