# HG changeset patch # User Rob Landley # Date 1328675159 21600 # Node ID 7cff5420c90a347dd5f47eb40c72593e93fd2554 # Parent a64003e250d49e928d04e36b5eee7b2fddb2d00d More cmp.c shrinkage. Abuse loopfiles() to handle both arguments, caching the first pass in globals. That eliminates get_fd() since loopfiles already knows how to handle "-" arg. Chop toybuf in half and use half for each file, eliminating malloc/free. main() becomes just a call to loopfiles(), which does all open/close. diff -r a64003e250d4 -r 7cff5420c90a toys/cmp.c --- a/toys/cmp.c Tue Feb 07 21:32:32 2012 -0600 +++ b/toys/cmp.c Tue Feb 07 22:25:59 2012 -0600 @@ -25,72 +25,67 @@ #define FLAG_s 1 #define FLAG_l 2 -int get_fd(char *file) -{ +DEFINE_GLOBALS( int fd; + char *name; +) + +#define TT this.cmp + +// This handles opening the file and - if (!strcmp(file,"-")) fd=0; - else fd = xopen(file, O_RDONLY); - return fd; -} +void do_cmp(int fd, char *name) +{ + int i, len1, len2, min_len, size = sizeof(toybuf)/2; + long byte_no = 1, line_no = 1; + char *buf2 = toybuf+size; -void do_cmp(int fd1, int fd2, char *file1, char *file2, char *buf1, char *buf2, - size_t size) -{ - int i, len1, len2, min_len; - size_t byte_no = 1, line_no = 1; + // First time through, cache the data and return. + if (!TT.fd) { + TT.name = name; + // On return the old filehandle is closed, and this assures that even + // if we were called with stdin closed, the new filehandle != 0. + TT.fd = dup(fd); + return; + } for (;;) { - len1 = read(fd1, buf1, size); - len2 = read(fd2, buf2, size); + len1 = readall(TT.fd, toybuf, size); + len2 = readall(fd, buf2, size); min_len = len1 < len2 ? len1 : len2; for (i=0; i