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 cmp_main(int argc, char *argv[])
     10 {
     11     int c;
     12     int fd1, fd2;
     13 	char buf1[4096], buf2[4096];
     14     int res, res1, res2;
     15 	int rv = 0;
     16 	int i;
     17 	int filepos = 0;
     18 
     19 	int show_byte = 0;
     20 	int show_all = 0;
     21 	int limit = 0;
     22 
     23     do {
     24         c = getopt(argc, argv, "bln:");
     25         if (c == EOF)
     26             break;
     27         switch (c) {
     28         case 'b':
     29             show_byte = 1;
     30             break;
     31         case 'l':
     32             show_all = 1;
     33             break;
     34         case 'n':
     35             limit = atoi(optarg);
     36             break;
     37         case '?':
     38             fprintf(stderr, "%s: invalid option -%c\n",
     39                 argv[0], optopt);
     40             exit(1);
     41         }
     42     } while (1);
     43 
     44     if (optind + 2 != argc) {
     45         fprintf(stderr, "Usage: %s [-b] [-l] [-n count] file1 file2\n", argv[0]);
     46         exit(1);
     47     }
     48 
     49     fd1 = open(argv[optind], O_RDONLY);
     50     if(fd1 < 0) {
     51         fprintf(stderr, "could not open %s, %s\n", argv[optind], strerror(errno));
     52         return 1;
     53     }
     54 
     55     fd2 = open(argv[optind+1], O_RDONLY);
     56     if(fd2 < 0) {
     57         fprintf(stderr, "could not open %s, %s\n", argv[optind+1], strerror(errno));
     58         return 1;
     59     }
     60 
     61     while(1) {
     62         res1 = read(fd1, &buf1, sizeof(buf1));
     63         res2 = read(fd2, &buf2, sizeof(buf2));
     64 		res = res1 < res2 ? res1 : res2;
     65 		if(res1 == 0 && res2 == 0) {
     66 			return rv;
     67 		}
     68 		for(i = 0; i < res; i++) {
     69 			if(buf1[i] != buf2[i]) {
     70 				printf("%s %s differ byte %d", argv[optind], argv[optind+1], filepos + i);
     71 				if(show_byte)
     72 					printf(" 0x%02x 0x%02x", buf1[i], buf2[i]);
     73 				printf("\n");
     74 				if(!show_all)
     75 					return 1;
     76 				rv = 1;
     77 			}
     78 			if(limit) {
     79 				limit--;
     80 				if(limit == 0)
     81 					return rv;
     82 			}
     83 		}
     84 		if(res1 != res2 || res < 0) {
     85 			printf("%s on %s\n", res < 0 ? "Read error" : "EOF", res1 < res2 ? argv[optind] : argv[optind+1]);
     86 			return 1;
     87 		}
     88 		filepos += res;
     89     }
     90 }
     91