home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / prof_c / 10dump / hexdump.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-11  |  1.6 KB  |  76 lines

  1. /*
  2.  *    hexdump -- read data from an open file and "dump"
  3.  *    it in side-by-side hex and ASCII to standard output
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <ctype.h>
  9. #include <local\std.h>
  10.  
  11. #define LINEWIDTH    80
  12. #define NBYTES        16
  13. #define WORD        0xFFFF
  14. #define RGHTMARK    179
  15. #define LEFTMARK    179
  16. #define DEL        0x7F
  17.  
  18. int hexdump(fd, strip)
  19. int fd;
  20. BOOLEAN strip;
  21. {
  22.     unsigned char i;
  23.     int n;            /* bytes per read operation */
  24.     unsigned long offset;    /* bytes from start of file */
  25.     char inbuf[BUFSIZ + 1], outbuf[LINEWIDTH + 1];
  26.     char hexbuf[5];
  27.     register char *inp, *outp;
  28.  
  29.     extern char *byte2hex(unsigned char, char *);
  30.     extern char *word2hex(unsigned int, char *);
  31.  
  32.     offset = 0;
  33.     while ((n = read(fd, inbuf, BUFSIZ)) != 0) {
  34.         if (n == -1)
  35.             return FAILURE;
  36.         inp = inbuf;
  37.         while (inp < inbuf + n) {
  38.             outp = outbuf;
  39.  
  40.             /* offset in hex */
  41.             outp += sprintf(outp, "%08lX",
  42.                 offset + (unsigned long)(inp - inbuf));
  43.             *outp++ = ' ';
  44.  
  45.             /* block of bytes in hex */
  46.             for (i = 0; i < NBYTES; ++i) {
  47.                 *outp++ = ' ';
  48.                 strcpy(outp, byte2hex(*inp++, hexbuf));
  49.                 outp += 2;
  50.             }
  51.             *outp++ = ' ';
  52.             *outp++ = ' ';
  53.             *outp++ = (strip == TRUE) ? '|' : LEFTMARK;
  54.  
  55.             /* same block of bytes in ASCII */
  56.             inp -= NBYTES;
  57.             for (i = 0; i < NBYTES; ++i) {
  58.                 if (strip == TRUE && (*inp < ' ' || *inp >= DEL))
  59.                     *outp = '.';
  60.                 else if (iscntrl(*inp))
  61.                     *outp = '.';
  62.                 else
  63.                     *outp = *inp;
  64.                 ++inp;
  65.                 ++outp;
  66.             }
  67.             *outp++ = (strip == TRUE) ? '|' : RGHTMARK;
  68.             *outp++ = '\n';
  69.             *outp = '\0';
  70.             fputs(outbuf, stdout);
  71.         }
  72.         offset += n;
  73.     }
  74.     return SUCCESS;
  75. }
  76.