[comp.sys.ibm.pc] Cheap HEX Dumper for UNIX and PC's

jps@bsdpkh.UUCP (05/06/87)

Someone was asking for a quick and dirty hex dumper for PC's.
This one works on UNIX, PC's, and just about anything else with
a decent C compiler.  I compiled it using Microsoft C with no
changes.  Have fun.


			       Jim Silas
			       ATT Altamonte Springs, Fl.

--------------------------- Cut Here -------------------------------
/* Produce a hex dump of a file with ASCII on the side */
#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
  int i;
  FILE *stream;

  if(argc == 1) dump(stdin);
  else
  {
    for(i = 1; i < argc; i++)
    {
      if(argc > 2) printf("\n>>>>>> %s:", argv[i]);
      if((stream = fopen(argv[i], "rb")) == NULL)
      {
        fprintf(stderr, "Can`t open %s\n", argv[i]);
        continue;
      }
      dump(stream);
      fclose(stream);
    }
  }
}

dump(stream)
FILE *stream;
{
  int i, n, size, endaddr;
  char *cp, *lp;
  char b[16];        /* input buffer */
  char l[80];        /* line image buffer */

  size = 0;
  while((n = fread(b, 1, 16, stream)) > 0)
  {
    endaddr = sprintf(l, " %8d %6x: ", size, size);
    cp = l + endaddr;
    for(i = 0, lp = b; i < 16; i++)
    {
      cp += sprintf(cp, "%02x", (0x0ff & *lp++));
      if(i == 3 || i == 7 || i == 11) *cp++ = ' ';
    }
    *cp++ = ' ';
    *cp++ = ' ';
    *cp++ = ' ';
    if(n < 16)        /* last line short? */
    {
      /* Locate hex code for last character: */
      lp = l + endaddr + 2*n + n/4;
      /* Blank out trailing hex codes: */
      while(lp < l + 37 + endaddr) *lp++ = ' ';
    }
    lp = l + 37 + endaddr;
    *lp++ = '[';
    cp = b;
    for(i = 0; i < n; i++)
    {
      if((cp[i] > 0x1f) && (cp[i] < 0x7f)) *lp++ = cp[i];
      else *lp++ = '.';
    }
    *lp++ = ']';
    *lp++ = '\0';
    *lp++ = '\n';
    fprintf(stdout,"\n%s", l);
    size += n;
  }
  fputc('\n', stdout);
}