[hackers] [sbase] sort: Move lines and nlines globals into a struct || Robert Ransom
changeset: 125:6ce18e295316
user: Robert Ransom <rransom.8774_AT_gmail.com>
date: Mon May 21 20:09:44 2012 +0000
files: sort.c
description:
sort: Move lines and nlines globals into a struct
diff -r e0d5f6454887 -r 6ce18e295316 sort.c
--- a/sort.c Sun May 20 14:38:52 2012 +0000
+++ b/sort.c Mon May 21 20:09:44 2012 +0000
_AT_@ -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[])
_AT_@ -34,33 +40,33 @@
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);
}
Received on Tue May 22 2012 - 13:08:45 CEST
This archive was generated by hypermail 2.3.0
: Tue May 22 2012 - 13:12:10 CEST