gpt4 book ai didi

以二进制格式组合两个文件

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:46 25 4
gpt4 key购买 nike

我写了这段代码来测试合并两个文件:

 long getFileSize(char *filename)
{
FILE* fp=fopen(filename,"rb");
fseek(fp,0,SEEK_END);
long size=ftell(fp);
fclose(fp);
return size;
}



long lengthA = getFileSize(argv[1]);
long lengthB = getFileSize(argv[2]);
printf("sizeof %s is:%d\n",argv[1],lengthA);
printf("sizeof %s is %d\n",argv[2],lengthB);

void *pa;
void *pb;
FILE* fp=fopen(argv[1],"rb");
fread(pa,1,lengthA,fp);
fclose(fp);
FILE* fpn=fopen(argv[2],"rb");
fread(pb,1,lengthB,fpn);
fclose(fpn);
printf("pointerA is:%p;pointerB is:%p\n",pa,pb);

FILE *ff=fopen("test.pack","wb");
fwrite(pa,1,lengthA,ff);
fwrite(pb,1,lengthB,ff);
fclose(ff);

long lengthFinal = getFileSize("test.pack");

printf("Final size:%i\n",lengthFinal);

但是我不知道数据是否等于 getFileSize 的返回值,控制台打印清楚地表明它有问题,但我无法弄清楚:

sizeof a.zip is:465235
sizeof b.zip is 107814
pointerA is:0x80484ec;pointerB is:0x804aff4
Final size:255270

因为我知道每个文件的长度,所以我可以使用 fseek 来恢复它们,对吗?这就是我的想法。

最佳答案

*pa*pb 需要指向一些内存,文件内容将被读取到。

因此,使用lengthA*sizeof(char)lengthB*sizeof(char) 为这两个缓冲区执行malloc 并传递它们为 fread 分配缓冲区:

pa = malloc(lengthA*sizeof(char));
pb = malloc(lengthB*sizeof(char));
...
fread(pa,sizeof(char),lengthA,fp);
...
fread(pb,sizeof(char),lengthB,fpn);

此外,fread 返回实际读取的项目数。还要检查这个!

摘自 man fread :

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

关于以二进制格式组合两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8589055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com