From b1f8ab7810f7a897846913046926d52c7c31a6a2 Mon Sep 17 00:00:00 2001 From: cuz Date: Sun, 29 Dec 2002 20:19:37 +0000 Subject: [PATCH] Fixed an error: The final linefeed got removed git-svn-id: svn://svn.cc65.org/cc65/trunk@1857 b7a2c559-68d2-44c3-8de9-860c34a00d81 --- libsrc/common/fgets.c | 49 ++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/libsrc/common/fgets.c b/libsrc/common/fgets.c index 7a51e4598..18fc29a6c 100644 --- a/libsrc/common/fgets.c +++ b/libsrc/common/fgets.c @@ -14,41 +14,43 @@ char* fgets (char* s, unsigned size, FILE* f) { - int i, c; + int i = 0; + int c; - /* We do not handle the case "size == 0" here */ - i = 0; --size; - while (i < size) { + if (size == 0) { + /* Invalid size */ + _errno = EINVAL; + return 0; + } + + /* Read input */ + i = 0; + while (--size) { /* Get next character */ - c = fgetc (f); - if (c == EOF) { - s [i] = 0; + if ((c = fgetc (f)) == EOF) { + s[i] = '\0'; /* Error or EOF */ - if (f->f_flags & _FERROR) { - /* ERROR */ - return 0; + if ((f->f_flags & _FERROR) != 0 || i == 0) { + /* ERROR or EOF on first char */ + return 0; } else { - /* EOF */ - if (i) { - return s; - } else { - return 0; - } + /* EOF with data already read */ + break; } } /* One char more */ - s [i++] = c; + s[i++] = c; - /* Stop at end of line */ - if (c == '\n') { - break; - } + /* Stop at end of line */ + if (c == '\n') { + break; + } } - /* Replace newline by NUL */ - s [i-1] = '\0'; + /* Terminate the string */ + s[i] = '\0'; /* Done */ return s; @@ -56,4 +58,3 @@ char* fgets (char* s, unsigned size, FILE* f) - -- 2.39.5