【问题标题】:Error with fread() in c, not having expected oututc中的fread()出错,没有预期的输出
【发布时间】:2018-03-27 18:50:31
【问题描述】:

我正在为我的一个类制作校验和算法,我想读取两个二进制文件并通过校验和算法运行它们。校验和算法有效(我尝试在终端中输入我想要的内容并且它有效)但我无法让我的 fread() 工作。我试过打印输出,他们打印正确的东西,但最后是一堆其他随机数字和字母。

这是我的代码:

int main(int argc, char *argv[])
{
  FILE *ptr1;
  FILE *ptr2;

  ptr1 = fopen("test1.bin","rb");
  ptr2 = fopen("test2.bin","rb");

  char file1[sizeof(ptr1)], file2[sizeof(ptr2)];
  char sum[sizeof(ptr1)], comp[sizeof(ptr1)];

  fread(file1,sizeof(file1),1,ptr1);
  fread(file2,sizeof(file2),1,ptr2);

  fclose(ptr1);
  fclose(ptr2);



/* char file1[20], file2[20];
  char sum[20], comp[20];

  printf("enter 1\n");
  scanf("%s",&file1);
  printf("enter 2\n");
  scanf("%s",&file2);*/

  if(strlen(file1)==strlen(file2)) {
      char next='0';
      int length = strlen(file1);

      for(int i=length-1;i>=0;i--)
    {
      if(file1[i]=='0' && file2[i]=='0' && next=='0')
        {
          sum[i]='0';
          next='0';
        }
      else if(file1[i]=='0' && file2[i]=='0' && next=='1')
        {
          sum[i]='1';
          next='0';
        }
      else if(file1[i]=='0' && file2[i]=='1' && next=='0')
        {
          sum[i]='1';
          next='0';
        }
      else if(file1[i]=='0' && file2[i]=='1' && next=='1')
        {
          sum[i]='0';
          next='1';
        }
      else if(file1[i]=='1' && file2[i]=='0' && next=='0')
        {
          sum[i]='1';
          next='0';
        }
      else if(file1[i]=='1' && file2[i]=='0' && next=='1')
        {
          sum[i]='0';
          next='1';
        }
      else if(file1[i]=='1' && file2[i]=='1' && next=='0')
        {
          sum[i]='0';
          next='1';
        }
      else if(file1[i]=='1' && file2[i]=='1' && next=='1')
        {
          sum[i]='1';
          next='1';
        }
      else
        break;
    }

      for (int i=0;i<length;i++)
    {
      if(sum[i]=='0')
        comp[i]='1';
      else
        comp[i]='0';
    }

      if(next=='1')
    next='0';
      else
    next='1';

      printf("\nChecksum=%c%s",next, comp);
  }
  else {
    printf("\nInput Lengths do not match");
  }
}

test1.bin 和 test2.bin 是两个包含 8 字节二进制文件的文件。我试过使用

printf("this is file 1 %s\n", file1)
printf("this is file 2 %s\n", file2)

帮助调试并输出

this is file 1 01001001dL
this is file 2 01001000P5L

我的错误是什么?我不太擅长 C,所以我确信它很简单。

【问题讨论】:

  • sizeof(file1) 不返回磁盘上文件的大小;它给出了file1 的内存大小,这是一个指针。您应该将文件的长度(或至少要读取的长度)作为fread 的第二个参数传递。因为您可能只从每个文件中读取 4 个字节。您还在对可能不是空终止的二进制数据执行strlen,这是一个坏主意。

标签: algorithm fopen checksum fread


【解决方案1】:

您为file1 分配sizeof(ptr1) 字节,但这意味着FILE* 类型的大小,可能是4。如果您知道您的文件正好包含8 个字节,请在此处写入8。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 2019-08-04
    • 2020-04-17
    • 2018-09-18
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多