简体   繁体   English

通过fread()读取二进制文件

[英]Reading a binary file via fread()

How can i read it back so that I can see the contents in my console itself? 如何读回它,以便可以在控制台本身中看到内容?
I used this way: 我用这种方式:

n = fread(buffer, sizeof(buffer), 1, fp);
printf("0x%x", buffer);

Here I am getting only 1 byte output, but the file contains 72 bytes. 在这里,我只得到1个字节的输出,但是文件包含72个字节。

As Yves Daoust pointed out, %x formatter expects a single byte. 正如Yves Daoust指出的那样,%x格式化程序期望一个字节。 Looping through the values will print all of them in hex. 遍历所有值将以十六进制打印所有值。

n = fread(buffer, 1, sizeof(buffer), fp);

int i=0;
for(i=0; i<n; i++)
{
    printf("0x%x ", buffer[i]);
}

Side note about fread: 关于fread的旁注:

The second parameter to fread is size of each member you want to read whereas the third parameter holds total length of data you want to read (man page: http://www.manpagez.com/man/3/fread/ ) Although it may not have a visible impact in this case, in your code sample the two arguments seems to have been swapped. 到第二个参数fread是你想读而第三个参数每个成员的大小持有要读取数据的总长度(手册页: http://www.manpagez.com/man/3/fread/ )虽然在这种情况下可能没有明显的影响,在您的代码示例中,两个参数似乎已经交换了。

The %x format descriptor expects a single value, it does not handle arrays. %x格式描述符期望单个值,它不处理数组。 You need to printf the 72 bytes one by one in a loop. 您需要循环循环打印72个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM