码迷,mamicode.com
首页 > 其他好文 > 详细

爱上C之:自制hexdump「二进制字节码查看」

时间:2016-09-21 09:07:05      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

 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”的功能

爱上C之:自制hexdump「二进制字节码查看」

标签:

原文地址:http://www.cnblogs.com/hadex/p/5891319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!