使用多个缓冲区复制二进制文件会导致错误的md5校验和

时间:2016-12-02 04:15:15

标签: c file

我有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}打开文件。

1 个答案:

答案 0 :(得分:1)

    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校验和正确