From de98360cbf57ae882bd926964305bbc0da6d537e Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Mon, 19 Aug 2024 01:48:17 +0200 Subject: toilet: don't use getline --- src/toilet.c | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) (limited to 'src/toilet.c') diff --git a/src/toilet.c b/src/toilet.c index 717afa4..ff51ba8 100644 --- a/src/toilet.c +++ b/src/toilet.c @@ -21,6 +21,8 @@ static int modeMap; +#define BUF_SIZE 4096 + static void usage(FILE *f) { fprintf(f, "Gebruik: toilet [-nchV] [BESTAND]...\n" @@ -77,16 +79,23 @@ static char** parse_options(int argc, char **argv, int *modeMap) { static size_t count_lines(char *fname, FILE *f) { size_t nlines = 0; + bool last_was_nl = false; + + while (!feof(f)) { + static char buf[BUF_SIZE]; + const size_t n = fread(buf, 1, BUF_SIZE, f); - { - char *line = NULL; - size_t linen = 0; - while ((errno = 0, getline(&line, &linen, f)) != -1) { - nlines++; + for (size_t i = 0; i < n; i++) { + last_was_nl = false; + if (buf[i] == '\n') { + nlines++; + last_was_nl = true; + } } - free(line); } + if (!last_was_nl) nlines++; + if (errno != 0) { printf("toilet: fout bij lezen uit bestand '%s'\n", fname); exit(1); @@ -97,7 +106,6 @@ static size_t count_lines(char *fname, FILE *f) { } static size_t count_words(FILE *f) { -#define BUF_SIZE 4096 size_t nwords = 0; while (!feof(f)) { @@ -115,8 +123,6 @@ static size_t count_words(FILE *f) { rewind(f); return nwords; - -#undef BUF_SIZE } static size_t get_count(enum MODE mode, char *fname, FILE *f) { @@ -148,7 +154,9 @@ static int process(char *fname, bool isstdin) { printf("%li ", count); } } - printf("%s\n", fname); + + if (fname != NULL) printf("%s", fname); + putchar('\n'); if (!isstdin) fclose(f); return 0; -- cgit v1.2.3-70-g09d2