【问题标题】:Reading binary file in C wrong output在 C 中读取二进制文件错误输出
【发布时间】:2014-03-24 10:50:51
【问题描述】:

我正在尝试读取二进制文件并将其中的每个字节打印为 2hex 数字,但是当 我到了一个空间,我的程序在应该是 '20' 时打印 '0',它每 20 次打印一次

我的输出0 17 FF FF FF FF 0 0 17 FF FF FF FF FF 0 0 0 FF 0 0

http://www.percederberg.net/tools/text_converter.html的输出

20 17 FF FF FF FF 20 20 17 FF FF FF FF FF 20 20 20 FF 20 20

有谁知道发生了什么? 文件 = ÿÿÿÿ ÿÿÿÿÿ ÿ

//Read the test.bin file!!
#include<stdio.h>
   char initial[] = "test.bin";
struct rec{
   unsigned char mydata;
};
int readfile(char []){
   int counter;
   FILE *ptr_myfile;
   struct rec my_record;
   ptr_myfile=fopen(initial,"r");
   if (!ptr_myfile){
      printf("Unable to open file!");
      return 1;
   }
   for ( counter=1; counter <= 20; counter++){
      fread(&my_record,sizeof(struct rec),1,ptr_myfile);
      printf("%X\n",my_record.mydata);      
   }
   fclose(ptr_myfile);
   return 0;
}
int main(){
   readfile(initial);
   return 0;
}

【问题讨论】:

  • 你应该检查fread()的返回。如果 test.bin 是一个空文件,你的程序会发生什么?
  • 如果文件是二进制文件,那么你应该open二进制模式。
  • 你确定文件在那些地方确实有 0x20,即你是用十六进制编辑器或 hexdump 看的,还是你唯一的参考在线转换器?
  • 尝试使用“rb”而不是“r”来打开 fopen。
  • 您是如何将二进制文件下载到该网站的?它只需要基于文本的编码吗?

标签: c binary hex


【解决方案1】:

代码可以正常工作,但在将二进制数据复制粘贴到网站时,0x00 字节最终会变成空格,在 ASCII 和兼容字符集中其值为 0x20

【讨论】:

  • 啊,好吧,我想我应该只使用该站点从十六进制转换 -> 二进制
猜你喜欢
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
相关资源
最近更新 更多