From e91185869d3494263fa4f633de73d305b52bbc48 Mon Sep 17 00:00:00 2001 From: Axel Kohlmeyer Date: Tue, 17 Aug 2021 09:25:25 -0400 Subject: [PATCH] fix bug in utils::fgets_trunc(). closes #2878 --- src/utils.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/utils.cpp b/src/utils.cpp index c0c15d0f3b..6a33fc044b 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -176,20 +176,23 @@ char *utils::fgets_trunc(char *buf, int size, FILE *fp) char dummy[MAXDUMMY]; char *ptr = fgets(buf, size, fp); - // EOF + // EOF? if (!ptr) return nullptr; int n = strlen(buf); - // line is shorter than buffer, append newline if needed, - if (n < size - 2) { + // check the string being read in: + // - if string is shorter than the buffer make sure it has a final newline and return + // - if string is exactly the size of the buffer and has a final newline return + // - otherwise truncate with final newline and read into dummy buffer until EOF or newline is found + if (n < size - 1) { if (buf[n - 1] != '\n') { buf[n] = '\n'; buf[n + 1] = '\0'; } return buf; - - // line fits exactly. overwrite last but one character. + } else if (buf[n - 1] == '\n') { + return buf; } else buf[size - 2] = '\n'; @@ -202,7 +205,7 @@ char *utils::fgets_trunc(char *buf, int size, FILE *fp) n = 0; } while (n == MAXDUMMY - 1 && ptr[MAXDUMMY - 1] != '\n'); - // return first chunk + // return truncated chunk return buf; }