1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
| #include <stdio.h>
#include <ctype.h> /* for isgraph() */
#define LINESIZE 16
void hd(FILE *in, FILE *out);
void print(FILE *fp,long addr,unsigned char *buf,int len);
int main(int argc, char *argv[])
{
int err = 0; /* returning no-zero on case of open error */
if ( argc < 2 )
{
hd( stdin, stdout); /* no command line argument */
}
else
{
int i;
for ( i = 1; i < argc; ++i ) /* the file arguments */
{
FILE *fp = fopen( argv[i], "r");
if ( NULL != fp ) /* open successful */
{
hd( fp, stdout);
fclose( fp); /* only fix number of opened files */
}
else
{
fprintf( stderr, "Can't open %s\n", argv[i]);
err = 1; /* at least one file open error */
}
}
}
return err; /* 0 == ok, 1 == error(s) */
}
void hd( FILE *in, FILE *out) /* for future improvement */
{
char ch;
unsigned char buffer[LINESIZE];/* %x requires unsigned */
int cnt = 0;
long addr = 0L; /* address inside the file */
while ( EOF != (ch = fgetc(in)) )
{
buffer[cnt++] = ch;
if ( LINESIZE == cnt ) /* buffer full */
{
print( out, addr, buffer, cnt); /* print buffer */
addr += cnt; /* == BUFSIZE, increment address */
cnt = 0;
}
}
/* if there are char(s) in buffer when EOF has occurs
we have to print them too */
if ( cnt > 0 )
{
print( out, addr, buffer, cnt);
}
}
void print(FILE *out,long addr,unsigned char *buf,int len)
{
int i;
fprintf( out, "%08lx | ", addr); /* address in hexa */
for ( i = 0; i < len; ++i )
{
fprintf( out, " %02x", buf[i]); /* a char in hexa */
}
for ( ; i < LINESIZE; ++i) /* spaces for last line */
{
fprintf( out, " ");
}
fprintf( out, " | ");
for ( i = 0; i < len; ++i) /* the chars or '.' */
{
fprintf( out, "%c", isgraph(buf[i]) ? buf[i] : '.');
}
fprintf( out, "\n"); /* very end of printed line */
}
|