From f7c1de35882f1f6eddada222efd798f0b66b6dcf Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Tue, 7 Feb 2012 22:25:59 -0600 Subject: 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. --- toys/cmp.c | 61 ++++++++++++++++++++++++++++--------------------------------- 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/toys/cmp.c b/toys/cmp.c index 0ee0ca7e..471952b2 100644 --- a/toys/cmp.c +++ b/toys/cmp.c @@ -25,72 +25,67 @@ config CMP #define FLAG_s 1 #define FLAG_l 2 -int get_fd(char *file) -{ +DEFINE_GLOBALS( int fd; + char *name; +) - if (!strcmp(file,"-")) fd=0; - else fd = xopen(file, O_RDONLY); - return fd; -} +#define TT this.cmp -void do_cmp(int fd1, int fd2, char *file1, char *file2, char *buf1, char *buf2, - size_t size) +// This handles opening the file and + +void do_cmp(int fd, char *name) { - int i, len1, len2, min_len; - size_t byte_no = 1, line_no = 1; + int i, len1, len2, min_len, size = sizeof(toybuf)/2; + long byte_no = 1, line_no = 1; + char *buf2 = toybuf+size; + + // 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