From 87b3bd7f2a3b0b1c3b9250886147396ef1c06eb9 Mon Sep 17 00:00:00 2001 From: June McEnroe Date: Tue, 12 Feb 2019 03:34:00 -0500 Subject: Use a proper fread-realloc loop in hi --- bin/hi.c | 22 +++++++++++++--------- bin/man1/hi.1 | 4 +--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/bin/hi.c b/bin/hi.c index 22823bcf..a4d0e835 100644 --- a/bin/hi.c +++ b/bin/hi.c @@ -682,18 +682,22 @@ int main(int argc, char *argv[]) { } if (!opts[Title]) opts[Title] = name; - size_t len = 32 * 1024; - if (file != stdin) { - struct stat stat; - int error = fstat(fileno(file), &stat); - if (error) err(EX_IOERR, "fstat"); - len = stat.st_size; - } + struct stat stat; + int error = fstat(fileno(file), &stat); + if (error) err(EX_IOERR, "fstat"); - char *str = malloc(len + 1); + size_t cap = (stat.st_mode & S_IFREG ? stat.st_size + 1 : 4096); + char *str = malloc(cap); if (!str) err(EX_OSERR, "malloc"); - len = fread(str, 1, len, file); + size_t len = 0, read; + while (0 < (read = fread(&str[len], 1, cap - len - 1, file))) { + len += read; + if (len + 1 < cap) continue; + cap *= 2; + str = realloc(str, cap); + if (!str) err(EX_OSERR, "realloc"); + } if (ferror(file)) err(EX_IOERR, "fread"); str[len] = '\0'; diff --git a/bin/man1/hi.1 b/bin/man1/hi.1 index 537acef5..c48fa796 100644 --- a/bin/man1/hi.1 +++ b/bin/man1/hi.1 @@ -1,4 +1,4 @@ -.Dd February 11, 2019 +.Dd February 12, 2019 .Dt HI 1 .Os . @@ -23,8 +23,6 @@ highlights the contents of a or standard input and formats it on standard output. -A maximum of 32K -is read from standard input. . .Pp The arguments are as follows: -- cgit 1.4.1