怎么编写一个函数来将两个文件合并起来呢?
现在有了这样的一段提示但是还是不懂,麻烦请帮忙给一个完整的代码,能加点注释就更好了,十分感谢!我真的理解不了
void FileCombine(FILE *fp1, FILE *fp2)
{
unsigned char *p;
long len;
len = FileSize(fp2);
p = (unsigned char *)malloc(len);
fread(p, len,1,fp2);
fwrite(p, len,1,fp1);
free(p);
}
我目前能想到的就是一个字符一个字符的往新文件中放。。。。
#include "stdio.h"
#include "stdlib.h"
int main() {
FILE *fp = fopen("test.txt", "rb");
if (fp == NULL) {
exit(1);
}
FILE *fp2 = fopen("test2.txt", "rb");
if (fp2 == NULL) {
exit(1);
}
FILE *fp3 = fopen("result.txt", "wb");
if (fp3 == NULL) {
exit(1);
}
int c1 = fgetc(fp);
int c2 = fgetc(fp2);
while (c1 != EOF) {
fputc(c1, fp3);
c1 = fgetc(fp);
}
while (c2 != EOF) {
fputc(c2, fp3);
c2 = fgetc(fp2);
}
fclose(fp);
fclose(fp2);
fclose(fp3);
return 0;
}
要看函数调用前,fp1是否移动到文件尾
这函数逻辑比较简单,FileSize函数获得被合并文件长度,然后申请相应的空间,fread将被合并文件数据读入到申请的空间,最后fwrite将读取的数据写入文件1的尾部,就完成两个文件合并了