我有 1 个文件,例如 abc.exe 当我使用 fread 将文件读入缓冲区并使用 fwrite 直接从该缓冲区本身写出时,我的输出文件具有正确的 md5 校验和。 当我将文件复制到中间缓冲区时,我得到不同的 md5 校验和,但文件大小与原始文件大小相同。 FILE_BLOCK_SIZE 为 1000
memset(BufContent, '\0', sizeof(BufContent));
while ((BufContentSz = fread(BufContent, sizeof(unsigned char), FILE_BLOCK_SIZE, fin)) > 0)
{
//ignore sum lines, merely for checking
//sum+=(int)strlen(BufContent);
//sum2+=BufContentSz;
unsigned char sendWithSeq2[ANY_BUFFER_SIZE_AS_NEEDED];
memset(sendWithSeq2,'\0',sizeof(sendWithSeq2));
strcat(sendWithSeq2,BufContent);
//wrong checksum obtained
fwrite(sendWithSeq2,sizeof(unsigned char), BufContentSz, fout);
//gives correct output
fwrite(BufContent, sizeof(unsigned char), BufContentSz, fout2);
memset(BufContent, '\0', sizeof(BufContent));
}
上面只是我为了检查问题出现在哪里而编写的演示代码。该问题似乎是由于使用中间缓冲区引起的。我尝试过各种缓冲区大小,甚至使用 strcpy、sprintf 来复制缓冲区,但仍然不起作用。
注意:相同的代码适用于文本文件甚至 csv 文件。两个输出文件都有正确的 md5 校验和。是的,我尝试过使用 {r,w} 和 {rb,wb} 打开文件。
最佳答案
memset(BufContent, '\0', sizeof(BufContent));
while ((BufContentSz = fread(BufContent, sizeof(unsigned char), FILE_BLOCK_SIZE, fin)) > 0)
{
unsigned char sendWithSeq2[ANY_BUFFER_SIZE_AS_NEEDED];
memset(sendWithSeq2,'\0',sizeof(sendWithSeq2));
memcpy (sendWithSeq2,BufContent,BufContentSz);
//wrong checksum obtained with strcat. Now works
fwrite(sendWithSeq2,sizeof(unsigned char), BufContentSz, fout);
//gives correct output
fwrite(BufContent, sizeof(unsigned char), BufContentSz, fout2);
memset(BufContent, '\0', sizeof(BufContent));
}
用 memcpy 替换 strcat,这使得 md5 校验和正确
关于使用超过 1 个缓冲区复制二进制文件会导致错误的 md5 校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40924702/