Esquif Esquif - 1 year ago 69
C Question

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

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 */

/* Read one byte */

/* Convert to string format */
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.

Answer Source

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));

    printf("<0x%x>\n", c);
    return 0;
  1. seeking is not needed
  2. if you want to read a byte use an unsigned char
  3. printf will do the format
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download