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

本文介绍了如何使用C语言通过命令行接口读取并输出文件内容为十六进制形式和可读文本形式,包括对文件路径的获取、文件的打开与关闭、内存缓冲区的设置、读取文件内容以及处理输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/hadex/archive/2012/09/21/5891319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值