Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming : how do I read and print out a byte from a binary file?

Tags:

c

I wish to open a binary file, to read the first byte of the file and finally to print the hex value (in string format) to stdout (ie, if the first byte is 03 hex, I wish to print out 0x03 for example). The output I get does not correspond with what I know to be in my sample binary, so I am wondering if someone can help with this.

Here is the code:

#include <stdio.h>
#include <fcntl.h>

int main(int argc, char* argv[])
{
int fd;
char raw_buf[1],str_buf[1];

fd = open(argv[1],O_RDONLY|O_BINARY);

    /* Position at beginning */
lseek(fd,0,SEEK_SET);

    /* Read one byte */
read(fd,raw_buf,1);

    /* Convert to string format */
sprintf(str_buf,"0x%x",raw_buf);
printf("str_buf= <%s>\n",str_buf);

close (fd);
return 0;   
}

The program is compiled as follows:

gcc rd_byte.c -o rd_byte

and run as follows:

rd_byte BINFILE.bin

Knowing that the sample binary file used has 03 as its first byte, I get the output:

str_buf= <0x22cce3>

What I expect is str_buf= <0x03>

Where is the error in my code?

Thank you for any help.

like image 314
Esquif Avatar asked Dec 02 '22 06:12

Esquif


1 Answers

You're printing the value of the pointer raw_buf, not the memory at that location:

sprintf(str_buf,"0x%x",raw_buf[0]);

As Andreas said, str_buf is also not big enough. But: no need for a second buffer, you could just call printf directly.

printf("0x%x",raw_buf[0]);
like image 157
Nick Meyer Avatar answered Dec 09 '22 11:12

Nick Meyer