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 10 int 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 if(res == 0) 72 break; 73 for(i = 0; i < res; i++) { 74 if((i & 15) == 0) { 75 printf("%08x: ", filepos + i); 76 } 77 lsum += buf[i]; 78 sum += buf[i]; 79 printf("%02x ", buf[i]); 80 if(((i & 15) == 15) || (i == res - 1)) { 81 printf("s %x\n", lsum); 82 lsum = 0; 83 } 84 } 85 if(res < 0) { 86 printf("Read error on %s, offset %d len %d, %s\n", argv[optind], filepos, read_len, strerror(errno)); 87 return 1; 88 } 89 filepos += res; 90 if(filepos == base + count) 91 break; 92 } 93 printf("sum %x\n", sum); 94 if(repeat) 95 sleep(repeat); 96 } while(repeat); 97 return 0; 98 } 99