fix bug in utils::fgets_trunc(). closes #2878

This commit is contained in:
Axel Kohlmeyer
2021-08-17 09:25:25 -04:00
parent a901427ee0
commit e91185869d

View File

@ -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;
}