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"
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);
}