C之:微代码——hexdump的简单实现

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <ctype.h>
 4 #define N 16
 5 int main(int argc,char *argv[])
 6 {
 7   char filename[FILENAME_MAX];//C's max length of file name.
 8   FILE *Pf=NULL;
 9   unsigned char buffer[N]; //Use unsigned char,prevent hex overflow.
10   int count,i,j;
11     if(argc==1)
12     {
13       printf("Please tell me your file name(with path if not in the current dir):\n");
14       scanf("%s",filename);
15     }
16     else
17     {
18     strcpy(filename,argv[1]);
19     }
20   Pf=fopen(filename,"rb");
21     setvbuf(Pf,NULL,_IOFBF,1024);//Set max buffer size to 1024 bytes.
22     if(Pf==0)
23     {
24       printf("Can't access %s!\n",filename);
25       return 0;
26     }
27   while(feof(Pf)==0)//check the end of file.
28   {
29     count=fread(buffer,1,sizeof(buffer),Pf);
30         printf("%08x  ",j);//number in hex.
31         j+=16;
32         for(i=0;i<sizeof(buffer);i++)
33     {
34             if(i<count)
35             {
36         printf("%02x ",buffer[i]);
37             }
38             else
39             {
40               printf("   ");
41             }
42     }
43     printf("| ");
44     for(i=0;i<sizeof(buffer);i++)
45     {
46             if(i<count)
47             {
48       printf("%c",isprint(buffer[i])?buffer[i]:'.');
49             }
50             else
51             {
52             printf(" ");
53             }
54     }
55     printf("|");
56     printf("\n");
57   }
58   fclose(Pf);
59   Pf=NULL;
60 }

注:本例实现了“hexdump -C”的功能

posted @ 2012-09-21 08:30  范辉  阅读(1304)  评论(0编辑  收藏  举报