sbase/cmp.c
FRIGN 695153ac18 Audit cmp(1)
1) Remove the return-value-enum, which is not necessary for a simple
   program like this.
2) Don't disallow both l and s to be specified. This is undefined
   behaviour defined by POSIX, so we don't start demanding things
   from the user.
3) Replace exit() with return (we are in main).
4) Refactor main loop to never return in the loop, but actually
   set the same-value and break, which increases readability.
5) Remove the final fclose()'s. The OS will take care of them, no
   need to become cleansy here.
6) Use idiomatic return-value using same. This concludes the
   increase of readability in the main-loop.
2015-03-11 11:16:40 +01:00

76 lines
1.2 KiB
C

/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
static void
usage(void)
{
enprintf(2, "usage: %s [-l | -s] file1 file2\n", argv0);
}
int
main(int argc, char *argv[])
{
FILE *fp[2];
size_t line = 1, n;
int lflag = 0, sflag = 0, same = 1, b[2];
ARGBEGIN {
case 'l':
lflag = 1;
break;
case 's':
sflag = 1;
break;
default:
usage();
} ARGEND;
if (argc != 2)
usage();
for (n = 0; n < 2; n++) {
if (argv[n][0] == '-' && !argv[n][1]) {
argv[n] = "<stdin>";
fp[n] = stdin;
} else {
if (!(fp[n] = fopen(argv[n], "r"))) {
if (!sflag)
weprintf("fopen %s:", argv[n]);
return 2;
}
}
}
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++;
continue;
} else if (b[0] == EOF || b[1] == EOF) {
if (!sflag)
weprintf("cmp: EOF on %s\n", argv[(b[0] != EOF)]);
same = 0;
break;
} else if (!lflag) {
if (!sflag)
printf("%s %s differ: byte %zu, line %zu\n",
argv[0], argv[1], n, line);
same = 0;
break;
} else {
printf("%zu %o %o\n", n, b[0], b[1]);
same = 0;
}
}
return !same;
}