Mercurial > hg > toybox
comparison toys/uniq.c @ 567:f1629eb63806
Refactor uniq.c a bit.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sat, 14 Apr 2012 22:34:34 -0500 |
parents | a095c02dc431 |
children |
comparison
equal
deleted
inserted
replaced
566:05617db1a337 | 567:f1629eb63806 |
---|---|
43 #define FLAG_d 2 | 43 #define FLAG_d 2 |
44 #define FLAG_u 1 | 44 #define FLAG_u 1 |
45 | 45 |
46 static char *skip(char *str) | 46 static char *skip(char *str) |
47 { | 47 { |
48 int field = 0; | 48 long nchars = TT.nchars, nfields; |
49 long nchars = TT.nchars; | 49 |
50 long nfields = TT.nfields; | |
51 // Skip fields first | 50 // Skip fields first |
52 while (nfields && *str) { | 51 for (nfields = TT.nfields; nfields; str++) { |
53 if (isspace((unsigned char)*str)) { | 52 while (*str && isspace(*str)) str++; |
54 if (field) { | 53 while (*str && !isspace(*str)) str++; |
55 field = 0; | 54 nfields--; |
56 nfields--; | |
57 } | |
58 } else if (!field) { | |
59 field = 1; | |
60 } | |
61 str++; | |
62 } | 55 } |
63 // Skip chars | 56 // Skip chars |
64 while (nchars-- && *str) | 57 while (*str && nchars--) str++; |
65 str++; | 58 |
66 return str; | 59 return str; |
67 } | 60 } |
68 | 61 |
69 static void print_line(FILE *f, char *line) | 62 static void print_line(FILE *f, char *line) |
70 { | 63 { |
71 if (TT.repeats == 0 && (toys.optflags & FLAG_d)) | 64 if (toys.optflags & (TT.repeats ? FLAG_u : FLAG_d)) return; |
72 return; | 65 if (toys.optflags & FLAG_c) fprintf(f, "%7lu ", TT.repeats + 1); |
73 if (TT.repeats > 0 && (toys.optflags & FLAG_u)) | 66 fputs(line, f); |
74 return; | 67 if (toys.optflags & FLAG_z) fputc(0, f); |
75 if ((toys.optflags & FLAG_c)) { | |
76 fprintf(f, "%7lu %s", TT.repeats + 1, line); | |
77 } else { | |
78 fprintf(f, "%s", line); | |
79 } | |
80 if (toys.optflags & FLAG_z) | |
81 fprintf(f, "%c", '\0'); | |
82 } | 68 } |
83 | 69 |
84 void uniq_main(void) | 70 void uniq_main(void) |
85 { | 71 { |
86 FILE *infile = stdin; | 72 FILE *infile = stdin, *outfile = stdout; |
87 FILE *outfile = stdout; | 73 char *thisline = NULL, *prevline = NULL, *tmpline, eol = '\n'; |
88 char *thisline = NULL; | 74 size_t thissize, prevsize = 0, tmpsize; |
89 char *prevline = NULL; | |
90 size_t thissize, prevsize = 0; | |
91 char *tmpline; | |
92 char eol = '\n'; | |
93 size_t tmpsize; | |
94 | 75 |
95 if (toys.optc >= 1) | 76 if (toys.optc >= 1) infile = xfopen(toys.optargs[0], "r"); |
96 infile = xfopen(toys.optargs[0], "r"); | 77 if (toys.optc >= 2) outfile = xfopen(toys.optargs[1], "w"); |
97 | 78 |
98 if (toys.optc >= 2) | 79 if (toys.optflags & FLAG_z) eol = 0; |
99 outfile = xfopen(toys.optargs[1], "w"); | |
100 | |
101 if (toys.optflags & FLAG_z) | |
102 eol = '\0'; | |
103 | 80 |
104 // If first line can't be read | 81 // If first line can't be read |
105 if (getdelim(&prevline, &prevsize, eol, infile) < 0) | 82 if (getdelim(&prevline, &prevsize, eol, infile) < 0) |
106 return; | 83 return; |
107 | 84 |