sbase

suckless unix tools
git clone git://git.2f30.org/sbase.git
Log | Files | Refs | README | LICENSE

commit e9d6735a9d15f42507f03533b5c00869fdc3aba7
parent 7565af0e31c214e6e470e07cca78df3bd0f7493b
Author: Robert Ransom <rransom.8774@gmail.com>
Date:   Mon, 21 May 2012 20:09:44 +0000

sort: Move lines and nlines globals into a struct
Diffstat:
sort.c | 32+++++++++++++++++++-------------
1 file changed, 19 insertions(+), 13 deletions(-)

diff --git a/sort.c b/sort.c @@ -8,12 +8,18 @@ #include "util.h" static int linecmp(const char **, const char **); -static void getlines(FILE *); static bool rflag = false; static bool uflag = false; -static char **lines = NULL; -static long nlines = 0; + +struct linebuf { + char **lines; + long nlines; +}; +#define EMPTY_LINEBUF {NULL, 0,} +static struct linebuf linebuf = EMPTY_LINEBUF; + +static void getlines(FILE *, struct linebuf *); int main(int argc, char *argv[]) @@ -34,33 +40,33 @@ main(int argc, char *argv[]) exit(2); } if(optind == argc) - getlines(stdin); + getlines(stdin, &linebuf); else for(; optind < argc; optind++) { if(!(fp = fopen(argv[optind], "r"))) eprintf("fopen %s:", argv[optind]); - getlines(fp); + getlines(fp, &linebuf); fclose(fp); } - qsort(lines, nlines, sizeof *lines, (int (*)(const void *, const void *))linecmp); + qsort(linebuf.lines, linebuf.nlines, sizeof *linebuf.lines, (int (*)(const void *, const void *))linecmp); - for(i = 0; i < nlines; i++) - if(!uflag || i == 0 || strcmp(lines[i], lines[i-1]) != 0) - fputs(lines[i], stdout); + for(i = 0; i < linebuf.nlines; i++) + if(!uflag || i == 0 || strcmp(linebuf.lines[i], linebuf.lines[i-1]) != 0) + fputs(linebuf.lines[i], stdout); return EXIT_SUCCESS; } void -getlines(FILE *fp) +getlines(FILE *fp, struct linebuf *b) { char *line = NULL; size_t size = 0; while(afgets(&line, &size, fp)) { - if(!(lines = realloc(lines, ++nlines * sizeof *lines))) + if(!(b->lines = realloc(b->lines, ++b->nlines * sizeof *b->lines))) eprintf("realloc:"); - if(!(lines[nlines-1] = malloc(strlen(line)+1))) + if(!(b->lines[b->nlines-1] = malloc(strlen(line)+1))) eprintf("malloc:"); - strcpy(lines[nlines-1], line); + strcpy(b->lines[b->nlines-1], line); } free(line); }