/* * $Id: hex.c,v 1.2 2005/11/27 19:58:23 sms Exp $ * www.pccl.demon.co.uk */ #include #include #include #include #include #include #include #define LINE_LEN 16 static char *sProgName; static int sOffset; static void resetDisplay (void) { sOffset = 0; } /* * Print out a block of memory as both Hex and text */ static void hexPrint ( char *aMsg /* Message buffer */ , int aLen /* Message length */ ) { int lIdx; /* Index through message */ /* * Print the offset */ printf (" %05d: ", sOffset); sOffset += LINE_LEN; /* * The Hex data */ for (lIdx = 0; lIdx < LINE_LEN; lIdx++) { if (lIdx < aLen) { printf ("%02x ", (unsigned char) aMsg[lIdx]); } else { printf (" "); } } printf (" : "); /* * The ASCII data */ for (lIdx = 0; lIdx < LINE_LEN; lIdx++) { char lChar = ' '; if (lIdx < aLen) { lChar = aMsg[lIdx]; } printf ("%c", (((lChar & 0x80) == 0) && isprint ((int) lChar)) ? lChar : '.' ); } printf ("\n"); } /* * Display the usage message */ static void usage ( FILE *aFp /* Stream to write */ ) { fprintf (aFp, "USAGE:\n"); fprintf (aFp, " %s file...\n", sProgName); fprintf (aFp, " -h help\n"); fprintf (aFp, "stdin is used as default\n"); } /* * Display all data from a stream in hex/text. */ static void displayFp( FILE *aFp ) { char lBuff [LINE_LEN]; /* Message buffer */ int lLen; /* and length */ while ((lLen = fread (lBuff, 1, LINE_LEN, aFp)) > 0) { hexPrint (lBuff, lLen); } } /* * Display a file in hex/text */ static void displayFile( char *aFile ) { FILE *lFp; /* File handle */ printf ("File: %s\n", aFile); lFp = fopen (aFile, "r"); resetDisplay (); if (lFp != NULL) { displayFp (lFp); fclose (lFp); } else { fprintf (stderr , "Cannot open %s, %s\n" , aFile , strerror (errno) ); exit (errno); } } /* * This program dumps out the named files in both hex and ascii. */ int main ( int aArgc /* Argument count */ , char *aArgv[] /* Arguments */ ) { char lOpt; /* Command line option */ int lArgIdx; /* Index through command line */ /* * Parse the command line */ sProgName = basename (aArgv[0]); while ((lOpt = getopt (aArgc, aArgv, "h")) != -1) { switch (lOpt) { case 'h': usage (stdout); exit (EINVAL); break; case '?': fprintf (stderr , "Unrecognised option: -%c\n" , optopt ); usage (stderr); exit (EINVAL); } } /* * Process each file */ if (optind < aArgc) { for (lArgIdx = optind; lArgIdx < aArgc; lArgIdx++) { displayFile (aArgv[lArgIdx]); } } else { displayFp (stdin); } exit (0); }