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
82
83
84
85
86
87
88
89
90
|
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LINE_LEN 16
int main(int argc, char **argv)
{
int readfd = 0;
if (argc == 2)
{
readfd = open(argv[1], O_RDONLY, 0666);
if (readfd < 0)
{
fprintf(stderr, "open: %s\n", strerror(errno));
return 1;
}
}
else if (argc > 2)
{
printf("usage: hd [file]\n");
return 1;
}
char lastbuf[LINE_LEN];
char curbuf[LINE_LEN];
int off = 0;
int lastrep = 0;
int bytes;
int i;
while ((bytes = read(readfd, curbuf, LINE_LEN)) > 0)
{
if (off > 0 && !memcmp(lastbuf, curbuf, LINE_LEN))
{
if (!lastrep)
{
printf("*\n");
lastrep = 1;
}
off += bytes;
continue;
}
lastrep = 0;
printf("%08x ", off);
off += bytes;
/* print bytes */
for (i = 0; i < LINE_LEN; ++i)
{
if (i < bytes)
{
printf("%02x ", (unsigned char)curbuf[i]);
}
else
{
printf(" ");
}
if (i == 7)
{
printf(" ");
}
}
/* show printable characters */
printf("|");
for (i = 0; i < bytes; ++i)
{
char c = curbuf[i];
if (c < 32 || c > 126)
{
printf(".");
}
else
{
printf("%c", c);
}
}
printf("|\n");
memcpy(lastbuf, curbuf, LINE_LEN);
}
printf("%08x\n", off);
if (readfd > 0)
{
close(readfd);
}
return 0;
}
|