简体   繁体   中英

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.

As Yves Daoust pointed out, %x formatter expects a single byte. 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:

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.

The %x format descriptor expects a single value, it does not handle arrays. You need to printf the 72 bytes one by one in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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