On Sun, Apr 21, 2013 at 01:33:55PM -0400, Ted Unangst wrote: > ok, it's not a rewrite, but I changed a lot of the lines. > > Use better types, check errors against -1, delete some casts, stack > buffer eliminates one malloc, braces for long blocks.
As long as you're in there, why not eliminate LIST as well and just use 'struct list'? .... Ken > > > Index: tee.c > =================================================================== > RCS file: /cvs/src/usr.bin/tee/tee.c,v > retrieving revision 1.7 > diff -u -p -r1.7 tee.c > --- tee.c 27 Oct 2009 23:59:44 -0000 1.7 > +++ tee.c 21 Apr 2013 07:27:16 -0000 > @@ -42,30 +42,41 @@ > #include <locale.h> > #include <err.h> > > -typedef struct _list { > - struct _list *next; > +typedef struct list { > + struct list *next; > int fd; > char *name; > } LIST; > LIST *head; > > -void add(int, char *); > +static void > +add(int fd, char *name) > +{ > + LIST *p; > + > + if ((p = malloc(sizeof(LIST))) == NULL) > + err(1, NULL); > + p->fd = fd; > + p->name = name; > + p->next = head; > + head = p; > +} > > int > main(int argc, char *argv[]) > { > LIST *p; > - int n, fd, rval, wval; > + int fd; > + ssize_t n, rval, wval; > char *bp; > int append, ch, exitval; > - char *buf; > -#define BSIZE (8 * 1024) > + char buf[8192]; > > setlocale(LC_ALL, ""); > > append = 0; > - while ((ch = getopt(argc, argv, "ai")) != -1) > - switch((char)ch) { > + while ((ch = getopt(argc, argv, "ai")) != -1) { > + switch(ch) { > case 'a': > append = 1; > break; > @@ -77,23 +88,24 @@ main(int argc, char *argv[]) > (void)fprintf(stderr, "usage: tee [-ai] [file ...]\n"); > exit(1); > } > + } > argv += optind; > argc -= optind; > > - if ((buf = malloc((size_t)BSIZE)) == NULL) > - err(1, NULL); > - > add(STDOUT_FILENO, "stdout"); > > - for (exitval = 0; *argv; ++argv) > - if ((fd = open(*argv, append ? O_WRONLY|O_CREAT|O_APPEND : > - O_WRONLY|O_CREAT|O_TRUNC, DEFFILEMODE)) < 0) { > + exitval = 0; > + while (*argv) { > + if ((fd = open(*argv, O_WRONLY | O_CREAT | > + (append ? O_APPEND : O_TRUNC), DEFFILEMODE)) == -1) { > warn("%s", *argv); > exitval = 1; > } else > add(fd, *argv); > + argv++; > + } > > - while ((rval = read(STDIN_FILENO, buf, BSIZE)) > 0) > + while ((rval = read(STDIN_FILENO, buf, sizeof(buf))) > 0) { > for (p = head; p; p = p->next) { > n = rval; > bp = buf; > @@ -106,7 +118,8 @@ main(int argc, char *argv[]) > bp += wval; > } while (n -= wval); > } > - if (rval < 0) { > + } > + if (rval == -1) { > warn("read"); > exitval = 1; > } > @@ -119,17 +132,4 @@ main(int argc, char *argv[]) > } > > exit(exitval); > -} > - > -void > -add(int fd, char *name) > -{ > - LIST *p; > - > - if ((p = malloc((size_t)sizeof(LIST))) == NULL) > - err(1, NULL); > - p->fd = fd; > - p->name = name; > - p->next = head; > - head = p; > } > >