hexcat.c

Denna kod är public domain. Om ni hittar fel eller vill ändra något i koden blir jag jätteglad om ni skickar dessa ändringar till jesper [at] fantasi [punkt] se.


/*
 * hexcat - Display a given file in hex-format.
 */

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
   FILE *input;
   char line[83];
   int i = 0;
   int value;
   int offset     = 12; /* Remember how many spaces etc we have */
   int charOffset = 49; /* Offset to ASCII display. */
   unsigned int lineNumber = 0;

   if (argc != 2)
   {
      fprintf(stderr, "Usage: hexcat <file name>\n");
      return EXIT_FAILURE;
   }

   if (!(input = fopen(argv[1], "r")))
   {
      fprintf(stderr, "Error opening file %s\n", argv[1]);
      return EXIT_FAILURE;
   }

   while ((value = fgetc(input)) != EOF)
   {
      int hexOffset;
      unsigned char ch = (unsigned char)value;

      if (i == 0)
         sprintf(line, "0x%08x  ", lineNumber++);
      else if (i % 4 == 0)
      {
         line[i * 2 + offset] = ' ';
         offset++;
      }
      hexOffset = i * 2 + offset;
      sprintf(line + hexOffset, "%02x", (unsigned int)ch);

      if (((ch & 0x7f) < ' ') || (ch == (unsigned char)127))
         ch = (unsigned char)183;

      line[i + charOffset] = ch;

      if (ch == '%')
         line[i + ++charOffset] = ch;

      i++;
      if (i >= 16)
      {
         line[47] = ' ';
         line[48] = ' ';
         line[charOffset + 16] = '\n';
         line[charOffset + 17] = '\0';
         printf(line);
         i = 0;
         offset = 12;
         charOffset = 49;
      }
   }

   if (i != 0)
   {
      for ( ; i < 16; i++)
      {
         int hexOffset;

         if (i % 4 == 0)
         {
            line[i * 2 + offset] = ' ';
            offset++;
         }
         hexOffset = i * 2 + offset;
         sprintf(line + hexOffset, "  ");
         line[i + charOffset] = ' ';
      }
      line[47] = ' ';
      line[48] = ' ';
      line[charOffset + 16] = '\n';
      line[charOffset + 17] = '\0';
      printf(line);
   }

   (void)fclose(input);
   return EXIT_SUCCESS;
}