sbase

suckless unix tools
git clone git://git.2f30.org/sbase.git
Log | Files | Refs | README | LICENSE

cmp.c (1424B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 
      6 #include "util.h"
      7 
      8 static void
      9 usage(void)
     10 {
     11 	enprintf(2, "usage: %s [-l | -s] file1 file2\n", argv0);
     12 }
     13 
     14 int
     15 main(int argc, char *argv[])
     16 {
     17 	FILE *fp[2];
     18 	size_t line = 1, n;
     19 	int ret = 0, lflag = 0, sflag = 0, same = 1, b[2];
     20 
     21 	ARGBEGIN {
     22 	case 'l':
     23 		lflag = 1;
     24 		break;
     25 	case 's':
     26 		sflag = 1;
     27 		break;
     28 	default:
     29 		usage();
     30 	} ARGEND
     31 
     32 	if (argc != 2 || (lflag && sflag))
     33 		usage();
     34 
     35 	for (n = 0; n < 2; n++) {
     36 		if (!strcmp(argv[n], "-")) {
     37 			argv[n] = "<stdin>";
     38 			fp[n] = stdin;
     39 		} else {
     40 			if (!(fp[n] = fopen(argv[n], "r"))) {
     41 				if (!sflag)
     42 					weprintf("fopen %s:", argv[n]);
     43 				return 2;
     44 			}
     45 		}
     46 	}
     47 
     48 	for (n = 1; ; n++) {
     49 		b[0] = getc(fp[0]);
     50 		b[1] = getc(fp[1]);
     51 
     52 		if (b[0] == b[1]) {
     53 			if (b[0] == EOF)
     54 				break;
     55 			else if (b[0] == '\n')
     56 				line++;
     57 			continue;
     58 		} else if (b[0] == EOF || b[1] == EOF) {
     59 			if (!sflag)
     60 				weprintf("cmp: EOF on %s\n", argv[(b[0] != EOF)]);
     61 			same = 0;
     62 			break;
     63 		} else if (!lflag) {
     64 			if (!sflag)
     65 				printf("%s %s differ: byte %zu, line %zu\n",
     66 				       argv[0], argv[1], n, line);
     67 			same = 0;
     68 			break;
     69 		} else {
     70 			printf("%zu %o %o\n", n, b[0], b[1]);
     71 			same = 0;
     72 		}
     73 	}
     74 
     75 	if (!ret)
     76 		ret = !same;
     77 	if (fshut(fp[0], argv[0]) | (fp[0] != fp[1] && fshut(fp[1], argv[1])) |
     78 	    fshut(stdout, "<stdout>"))
     79 		ret = 2;
     80 
     81 	return ret;
     82 }