一.本文主要内容是分割一个与合并几个文件,使用c语言实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*文件分割,path为要分割的文件路径name为文件名,count为分割数量,savepath为保存路径,返回-1表示分割失败,0表示成功*/
int splitFile(char *path, int count, char *savepath, char *savename)
{
FILE *F = fopen(path,"rb");
if (F == NULL)
{
return -1;
}
else
{
fseek(F, 0, SEEK_END);//将文件指针移动到文件末尾
int length = ftell(F);//计算文件指针到文件开头的字节数,即就是文件大小
int yushu = length % count;//余数
int size = length / count; //前面count-1份每一分大小为size,最后一份为size + yushu
for (int i = 1; i <= count; i++)
{
char savefile[100];
sprintf(savefile, "%s%d%s", savepath, i, savename);
printf("%s", savefile);
FILE *P = fopen(savefile, "wb");
if (P == NULL)
{
fclose(F);
return -1;
}
else
{
fseek(F, (i - 1)*size, SEEK_SET);
if (i == count)
{
for (int j = 0; j <= size + yushu; j++)
{
int c = fgetc(F);
fputc(c, P);
}
}
else
{
for (int j = 0; j < size; j++)
{
int c = fgetc(F);
fputc(c, P);
}
}
}
fclose(P);
}
fclose(F);
return 0;
}
}
/*合并文件,将文件list中每一行指定的文件按行顺序合并为一个大文件bigfile返回-1表示分割失败,0表示成功*/
int mergeFile(char *list,int count,char *bigfile)
{
FILE *F = fopen(list, "r");
FILE *BF = fopen(bigfile, "wb");
if (F == NULL || BF == NULL)
{
printf("打开文件失败");
return -1;
}
else
{
for (int i = 0; i < count; i++)
{
char str[200];
fgets(str, 200, F);//每次读取一行字符串,读到末尾为0
printf("%s", str);
int len = strlen(str);
str[len - 1] = '\0';
printf("%s", str);
FILE *P = fopen(str, "rb");
if (P == NULL)
{
printf("打开文件失败");
fclose(F);
fclose(BF);
return -1;
}
else
{
int c = fgetc(P);
while (c != EOF)
{
fputc(c, BF);
c = fgetc(P);
}
}
fclose(P);
}
}
fclose(F);
fclose(BF);
return 0;
}
void main()
{
//int i = splitFile("F:\\文件分割与合并.mp4", 4, "F:\\", "文件分割与合并.mp4");
//printf("%d", i);
mergeFile("F:\\list.txt",4, "F:\\he.mp4");
system("pause");
}
2.效果截图
3.list文件内容