开发者

How would I print out the address like the Hexdump function in UNIX

There I have this assignment where I am suppose to emulate the hexdump function from unix. I got my program to dump files into hex but i am having trouble printing the offset and the printable characters.

Here is my code:

/*performs a hex and an octal dump of a file*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 512

void hexdump(FILE *fp);
void octaldump(FILE *fp);

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

   if((fp = fopen(argv[1], "rb+")) == '\0')
   {
    perror("fopen");
    return 0;
   }

   hexdump(fp);

   return 0;
}

void hexdump(FILE *fp)
{
   char temp [LINESIZE];
   size_t i = 0;
   size_t linecount = 1;
   long int address = 0;


   while(fscanf(fp," %[^\n] ", temp) == 1)
   {
     printf("%5d", address);

     for(i = 0; i < strlen(temp); i++)
     {
        printf("%02x ", temp[i]);

        if(linecount == 16)
        {
            printf("\n");
            linecount = 0;          
        }
        linecount++;
     }
     printf(" | ");

     for(i = 0; i < strlen(temp); i++)
     {
         if(temp[i] < 32)
         {
            printf(".");
         }
         else
         {
             printf("%c", temp[i]);
         }
     }
     printf("\n");
    }
}

As i said above, my program is suppose to print the offset then the hex value of the file padded with 0's, then the printable characters of the file like so.

0000000 7f 2a 34 f3 21 00 00 00 00 00 00 00 00 00 00 00 | test file

I managed to print out the printable characters, but they appear after the hex part. So if one line of hexcode extends to the next line, it prints the printable characters on the nextline.

For example:

2a 3b 4d 3e 5f
12 开发者_开发百科43 23 43 | asfdg df

How do i get it to print whatever character appears after one line of the hex characters?

PS: For some reason my program doesn't pad 0's for some reason.

EDIT1: I got the offset part, i just keep adding 16 to my address variable and keep printing


Since this is homework, I'll just give you some pointers on how to approach your problem. I'll be as vague as I can so as to not interfere with your learning.

First of all, don't use fscanf if you're writing a hex dumper, use fread instead. The scanf family of functions are meant for text and hex dumpers are usually used with binary data.

If you use fread and read just enough bytes at a time to fill one line of output, then you can produce your desired output with two for loops (one for hex, one for characters) followed by a single newline.

As far as your zero padding problem goes, read the printf man page, your "%5d" format string needs a little bit more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜