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