title: C Programming : how do I read and print out a byte from a binary file?
body: <p>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.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;
  
  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= &lt;%s&gt;\n",str_buf);
  
  close (fd);
  return 0;   
  }
  </code></pre>
  
  <p>The program is compiled as follows:<p>
  gcc rd_byte.c -o rd_byte</p>
  
  <p>and run as follows:<p>
  rd_byte BINFILE.bin</p>
  
  <p>Knowing that the sample binary file used has 03 as its first byte, I get the output:</p>
  
  <p>str_buf= &lt;0x22cce3></p>
  
  <p>What I expect is 
  str_buf= &lt;0x03></p>
  
  <p>Where is the error in my code?</p>
  
  <p>Thank you for any help.</p>