Hex Dump

Dave Sinkula 0 Tallied Votes 227 Views Share

This is a quick and dirty example of a hex dump utility. Not much in the way of special features -- it just dumps the contents of a hard-coded filename in hex and also shows the characters. An example that can show the basics of making your own.

#include <stdio.h>
#include <ctype.h>

/**
 * Display the contents of a stream as hexadecimal bytes and text.
 * @param  file  pointer to a binary stream
 * @return the number of bytes in the file read
 */
size_t hexdump(FILE *file)
{
   unsigned char data[16];
   size_t i, j, size, count = 0;
   /*
    * Heading
    */
   fputs("         ", stdout); /* skip address area */
   for ( i = 0; i < sizeof data / sizeof *data; ++i )
   {
      printf("+%lX ", (long unsigned)i);
   }
   puts("Text");
   /*
    * Body
    */
   do {
      /* Read some data. */
      size = fread(data, sizeof *data, sizeof data / sizeof *data, file);
      if ( size )
      {
         /* Print the base address. */
         printf("%08lX ", (long unsigned)count);
         count += size; /* adjust the base address */
         /* Print the characters' hex values. */
         for ( i = 0; i < size; ++i )
         {
            printf("%02X ", data[i]);
         }
         /* Pad the hex values area if necessary. */
         for ( ++i; i <= sizeof data / sizeof *data; ++i )
         {
            fputs("   ", stdout);
         }
         /* Print the characters (use '.' for non-printing characters). */
         for ( j = 0; j < size; j++ )
         {
            putchar(isprint(data[j]) ? data[j] : '.');
         }
         putchar('\n');
      }
   } while ( size == sizeof data / sizeof *data ); /* Break on partial count. */
   return count;
}

int main(void)
{
   static const char filename[] = __FILE__; /* may not work on everywhere */
   FILE *file = fopen(filename, "rb");
   if ( file != NULL )
   {
      printf("%lu bytes\n", (long unsigned)hexdump(file));
      fclose(file);
   }
   else
   {
      perror(filename);
   }
   return 0;
}