I want to open a binary file to read the first byte of the file and finally print the hex value (in string format) in stdout (i.e. if the first byte is 03 hex, I want to print 0x03 for example). The output I get does not match what I know in my binary, so I'm wondering if anyone 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 do the following:
rd_byte BINFILE.bin
Knowing that the sample binary used has 03 as its first byte, I get the output:
str_buf = <0x22cce3>
What do I expect str_buf = <0x03>
Where is the error in my code?
Thanks for any help.
source share