C Programming : how do I read and print out a byte from a binary file?
c
Solution
Less is more...
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int fd;
unsigned char c;
/* needs error checking */
fd = open(argv[1], O_RDONLY);
read(fd, &c, sizeof(c));
close(fd);
printf("<0x%x>\n", c);
return 0;
}
- `seek`ing is not needed
- if you want to read a byte use an `unsigned char`
- `printf` will do the format
Problem
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.