hd.c revision b93e5812faffd3b6c5fb349072413aace31918d8
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <stdint.h>
5#include <unistd.h>
6#include <fcntl.h>
7#include <sys/ioctl.h>
8#include <errno.h>
9
10int hd_main(int argc, char *argv[])
11{
12    int c;
13    int fd;
14	unsigned char buf[4096];
15    int res;
16	int read_len;
17	int rv = 0;
18	int i;
19	int filepos = 0;
20	int sum;
21	int lsum;
22
23	int base = -1;
24	int count = 0;
25	int repeat = 0;
26
27    do {
28        c = getopt(argc, argv, "b:c:r:");
29        if (c == EOF)
30            break;
31        switch (c) {
32        case 'b':
33            base = strtol(optarg, NULL, 0);
34            break;
35        case 'c':
36            count = strtol(optarg, NULL, 0);
37            break;
38		case 'r':
39			repeat = strtol(optarg, NULL, 0);
40			break;
41        case '?':
42            fprintf(stderr, "%s: invalid option -%c\n",
43                argv[0], optopt);
44            exit(1);
45        }
46    } while (1);
47
48    if (optind + 1 != argc) {
49        fprintf(stderr, "Usage: %s [-b base] [-c count] [-r delay] file\n", argv[0]);
50        exit(1);
51    }
52
53    fd = open(argv[optind], O_RDONLY);
54    if(fd < 0) {
55        fprintf(stderr, "could not open %s, %s\n", argv[optind], strerror(errno));
56        return 1;
57    }
58
59	do {
60		if(base >= 0) {
61			lseek(fd, base, SEEK_SET);
62			filepos = base;
63		}
64		sum = 0;
65		lsum = 0;
66	    while(1) {
67			read_len = sizeof(buf);
68			if(count > 0 && base + count - filepos < read_len)
69				read_len = base + count - filepos;
70	        res = read(fd, &buf, read_len);
71			for(i = 0; i < res; i++) {
72				if((i & 15) == 0) {
73					printf("%08x: ", filepos + i);
74				}
75				lsum += buf[i];
76				sum += buf[i];
77				printf("%02x ", buf[i]);
78				if(((i & 15) == 15) || (i == res - 1)) {
79					printf("s %x\n", lsum);
80					lsum = 0;
81				}
82			}
83			if(res <= 0) {
84				printf("Read error on %s, offset %d len %d, %s\n", argv[optind], filepos, read_len, strerror(errno));
85				return 1;
86			}
87			filepos += res;
88			if(filepos == base + count)
89				break;
90	    }
91		printf("sum %x\n", sum);
92		if(repeat)
93			sleep(repeat);
94	} while(repeat);
95	return 0;
96}
97