morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

cmp.c (1543B)


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