sbase/cmp.c

74 lines
1.3 KiB
C
Raw Normal View History

2011-06-09 20:55:12 -04:00
/* See LICENSE file for copyright and license details. */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
2011-06-18 01:42:24 -04:00
#include "util.h"
enum { Same = 0, Diff = 1, Error = 2 };
2011-06-09 20:55:12 -04:00
2013-06-14 14:20:47 -04:00
static void
usage(void)
{
enprintf(Error, "usage: %s [-ls] file1 [file2]\n", argv0);
2013-06-14 14:20:47 -04:00
}
2011-06-09 20:55:12 -04:00
int
main(int argc, char *argv[])
{
2011-06-09 21:00:27 -04:00
bool lflag = false;
bool sflag = false;
2011-06-09 20:55:12 -04:00
bool same = true;
int b[2], i;
long line = 1, n = 1;
FILE *fp[2];
2013-06-14 14:20:47 -04:00
ARGBEGIN {
case 'l':
lflag = true;
break;
case 's':
sflag = true;
break;
default:
usage();
} ARGEND;
if (argc < 1 || argc > 2)
2013-06-14 14:20:47 -04:00
usage();
fp[0] = fopen(argv[0], "r");
if (!fp[0])
enprintf(Error, "fopen %s:", argv[0]);
fp[1] = stdin;
if (argc == 2)
fp[1] = fopen(argv[1], "r");
if (!fp[1])
enprintf(Error, "fopen %s:", argv[1]);
for(n = 1; ; n++) {
b[0] = getc(fp[0]);
b[1] = getc(fp[1]);
if(b[0] == EOF && b[1] == EOF)
break;
2011-06-09 20:55:12 -04:00
line++;
if(b[0] == b[1])
continue;
for(i = 0; i < 2; i++)
2011-06-18 01:42:24 -04:00
if(b[i] == EOF)
enprintf(Diff, "cmp: EOF on %s\n",
2014-03-04 05:41:19 -05:00
!argv[i] ? "<stdin>" : argv[i]);
2011-06-09 20:55:12 -04:00
if(!lflag) {
if(!sflag)
printf("%s %s differ: char %ld, line %ld\n",
argv[0], !argv[1] ? "<stdin>" : argv[1], n, line);
2011-06-18 01:42:24 -04:00
exit(Diff);
2013-06-14 14:20:47 -04:00
} else {
2011-06-09 20:55:12 -04:00
printf("%4ld %3o %3o\n", n, b[0], b[1]);
same = false;
}
}
2011-06-18 01:42:24 -04:00
return same ? Same : Diff;
2011-06-09 20:55:12 -04:00
}