sort: Move lines and nlines globals into a struct

This commit is contained in:
Robert Ransom 2012-05-21 20:09:44 +00:00
parent 7565af0e31
commit e9d6735a9d

32
sort.c
View File

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