freq

unnamed repository
Log | Files | Refs

commit 8225f9e5aa237f6a22c6d733a7dfe3f775f2d153
parent 4b36f0e5fa0b20f3dedbc30ba045f05bfb296148
Author: phoebos <ben@bvnf.space>
Date:   Mon, 21 Mar 2022 18:48:06 +0000

count from 1 and check for missing fields

Diffstat:
Mfreq.c | 26++++++++++++++++++--------
1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/freq.c b/freq.c @@ -58,7 +58,7 @@ print_freqs(void) { int main (int argc, char **argv) { - int c, field = 0; + int c, field = 1; while ((c = getopt(argc, argv, ":k:")) != -1) { switch (c) { case 'k': @@ -93,15 +93,18 @@ main (int argc, char **argv) { void freq(FILE *f, int field) { - char *line = NULL; + char *field_start, *line = NULL; size_t linelen = 0; - ssize_t n; - int cur_field, in_word; + ssize_t n, i; + int cur_field, in_word, linenum; + linenum = 0; while ((n = getline(&line, &linelen, f)) != -1) { - ssize_t i = 0; - char *field_start = line; - in_word = cur_field = 0; + linenum++; + i = 0; + field_start = line; + in_word = 0; + cur_field = 1; /* eat up whitespace at front */ while (isspace(line[i])) i++; @@ -112,7 +115,9 @@ freq(FILE *f, int field) { line[i] = '\0'; goto field_found; } - cur_field++; + if (i < n - 1) + /* the last byte is probably '\n' and there is no next field */ + cur_field++; in_word = 0; } } else { @@ -121,6 +126,11 @@ freq(FILE *f, int field) { in_word = 1; } } + if (cur_field != field) { + /* didn't find the specified field */ + fprintf(stderr, "freq: warning: field %d not found on line %d\n", field, linenum); + continue; + } field_found: //fprintf(stderr, "found '%s'\n", field_start); update_record(field_start);