sbase/cmp.c

81 lines
1.4 KiB
C
Raw Normal View History

2011-06-10 00:55:12 +00:00
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2011-06-10 00:55:12 +00:00
#include <unistd.h>
2011-06-18 05:42:24 +00:00
#include "util.h"
enum { Same = 0, Diff = 1, Error = 2 };
2011-06-10 00:55:12 +00:00
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
enprintf(Error, "usage: %s [-l | -s] file1 file2\n", argv0);
2013-06-14 18:20:47 +00:00
}
2011-06-10 00:55:12 +00:00
int
main(int argc, char *argv[])
{
FILE *fp[2];
size_t i, line = 1, n = 1;
int lflag = 0, sflag = 0, same = 1, b[2];
2011-06-10 00:55:12 +00:00
2013-06-14 18:20:47 +00:00
ARGBEGIN {
case 'l':
lflag = 1;
2013-06-14 18:20:47 +00:00
break;
case 's':
sflag = 1;
2013-06-14 18:20:47 +00:00
break;
default:
usage();
} ARGEND;
if (argc != 2 || (lflag && sflag))
2013-06-14 18:20:47 +00:00
usage();
if (!strcmp(argv[0], argv[1]))
return Same;
for (i = 0; i < 2; i++) {
if (argv[i][0] == '-' && !argv[i][1])
argv[i] = "/dev/fd/0";
fp[i] = fopen(argv[i], "r");
if (!fp[i]) {
if (!sflag)
weprintf("fopen %s:", argv[i]);
exit(Error);
}
}
for (n = 1; ; n++) {
b[0] = getc(fp[0]);
b[1] = getc(fp[1]);
if (b[0] == b[1]) {
if (b[0] == EOF)
break;
else if (b[0] == '\n')
line++;
2011-06-10 00:55:12 +00:00
continue;
}
if (b[0] == EOF || b[1] == EOF) {
if (!sflag)
fprintf(stderr, "cmp: EOF on %s\n",
argv[(b[0] == EOF) ? 0 : 1]);
exit(Diff);
}
if (!lflag) {
if (!sflag)
printf("%s %s differ: byte %ld, line %ld\n",
argv[0], argv[1], n, line);
2011-06-18 05:42:24 +00:00
exit(Diff);
2013-06-14 18:20:47 +00:00
} else {
printf("%ld %o %o\n", n, b[0], b[1]);
same = 0;
2011-06-10 00:55:12 +00:00
}
}
2011-06-18 05:42:24 +00:00
return same ? Same : Diff;
2011-06-10 00:55:12 +00:00
}