diff options
Diffstat (limited to 'src/omd.c')
-rw-r--r-- | src/omd.c | 82 |
1 files changed, 10 insertions, 72 deletions
@@ -3,6 +3,7 @@ #include <stdlib.h> #include <string.h> #include <unistd.h> +#include "io/lines.h" #include "util/versie.h" #include "util/error.h" #include "util/debug.h" @@ -48,83 +49,20 @@ static void reverse_in_place(char *buf, size_t len) { } static void process(const char *fname, FILE *f) { - size_t cap = 4096; - char *buffer = malloc(cap); - if (!buffer) print_error_nomem("omd"); - - size_t cursor = 0; + struct file_lines fl; + if (!file_lines_open("omd", fname, f, &fl)) exit(1); while (true) { - DEBUG("cursor=%zu\n", cursor); - - // read a line - size_t linelen = 0; - while (true) { - // grow buffer when small - if (cap - cursor < 1024) { - cap *= 2; - if (cap == 0) { - fprintf(stderr, "omd: Regel te lang\n"); - exit(1); - } - DEBUG("realloc to cap %zu\n", cap); - buffer = realloc(buffer, cap); - if (!buffer) print_error_nomem("omd"); - } + struct string_view sv; + if (!file_lines_read(&fl, &sv)) break; - size_t nr = fread(buffer + cursor, 1, cap - cursor, f); - DEBUG("nr=%zu\n", nr); - if (nr == 0) { - if (feof(f)) { - if (cursor == 0) return; - linelen = cursor; - break; - } - if (fname) fprintf(stderr, "omd: Fout bij lezen van bestand '%s'\n", fname); - else fprintf(stderr, "omd: Fout bij lezen van standaardinvoer\n"); - exit(1); - } - char *p = memchr(buffer + cursor, '\n', nr); - cursor += nr; - if (p != NULL) { - linelen = p - buffer; - break; - } - } - - DEBUG("line with len %zu (cursor=%zu)\n", linelen, cursor); - - // we have a newline at cursor+linelen; print all lines that we already have in full - size_t linestart = 0; - while (true) { - reverse_in_place(buffer + linestart, linelen); - if (linestart + linelen < cap && buffer[linestart + linelen] == '\n') { - size_t nw = fwrite(buffer + linestart, 1, linelen + 1, stdout); - if (nw < linelen + 1) exit(1); - } else { - size_t nw = fwrite(buffer + linestart, 1, linelen, stdout); - if (nw < linelen) exit(1); - putchar('\n'); - // no newline in the buffer but nevertheless a completed line means that input is at EOF - goto cleanup; - } - - linestart += linelen + 1; - char *p = memchr(buffer + linestart, '\n', cursor - linestart); - if (p == NULL) { - DEBUG("no more newlines, moving back from %zu len %zu\n", linestart, cursor - linestart); - // move back whatever we have left - memmove(buffer, buffer + linestart, cursor - linestart); - cursor -= linestart; - break; - } - linelen = p - (buffer + linestart); - DEBUG("next line from %zu len %zu\n", linestart, linelen); - } + reverse_in_place(sv.s, sv.len); + size_t nw = fwrite(sv.s, 1, sv.len, stdout); + if (nw < sv.len) exit(1); + putchar('\n'); } -cleanup: - free(buffer); + file_lines_close(&fl); } int entry_omd(int argc, char **argv) { |