diff options
Diffstat (limited to 'toys/posix/sort.c')
-rw-r--r-- | toys/posix/sort.c | 47 |
1 files changed, 20 insertions, 27 deletions
diff --git a/toys/posix/sort.c b/toys/posix/sort.c index 4b3fe24d..9d2f2276 100644 --- a/toys/posix/sort.c +++ b/toys/posix/sort.c @@ -63,7 +63,6 @@ GLOBALS( void *key_list; int linecount; char **lines; - char *name; ) // The sort types are n, g, and M. @@ -276,37 +275,31 @@ static int compare_keys(const void *xarg, const void *yarg) return retval * ((flags&FLAG_r) ? -1 : 1); } -// Read each line from file, appending to a big array. -static void sort_lines(char **pline, long len) +// Callback from loopfiles to handle input files. +static void sort_read(int fd, char *name) { - char * line; + // Read each line from file, appending to a big array. - if (!pline) return; - line = *pline; - if (!FLAG(z) && len && line[len-1]=='\n') line[--len] = 0; - *pline = NULL; + for (;;) { + char * line = FLAG(z) ? get_rawline(fd, NULL, 0) : get_line(fd); - // handle -c here so we don't allocate more memory than necessary. - if (FLAG(c)) { - int j = FLAG(u) ? -1 : 0; + if (!line) break; - if (TT.lines && compare_keys((void *)&TT.lines, &line)>j) - error_exit("%s: Check line %d\n", TT.name, TT.linecount); - free(TT.lines); - TT.lines = (char **)line; - } else { - if (!(TT.linecount&63)) - TT.lines = xrealloc(TT.lines, sizeof(char *)*(TT.linecount+64)); - TT.lines[TT.linecount] = line; - } - TT.linecount++; -} + // handle -c here so we don't allocate more memory than necessary. + if (FLAG(c)) { + int j = FLAG(u) ? -1 : 0; -// Callback from loopfiles to handle input files. -static void sort_read(int fd, char *name) -{ - TT.name = name; - do_lines(fd, FLAG(z) ? '\0' : '\n', sort_lines); + if (TT.lines && compare_keys((void *)&TT.lines, &line)>j) + error_exit("%s: Check line %d\n", name, TT.linecount); + free(TT.lines); + TT.lines = (char **)line; + } else { + if (!(TT.linecount&63)) + TT.lines = xrealloc(TT.lines, sizeof(char *)*(TT.linecount+64)); + TT.lines[TT.linecount] = line; + } + TT.linecount++; + } } void sort_main(void) |