From 40a093ba3fb6a3b9f48e4625bd72d82eb18d5931 Mon Sep 17 00:00:00 2001 From: HanaMAshour <167436481+HanaMAshour@users.noreply.github.com> Date: Thu, 18 Apr 2024 15:39:31 +0000 Subject: [PATCH] tinystdio: fgets returns NULL only when EOF is reached According to the ISO/IEC_9899_1999, section:7.19.7.2 It is mentioned that when EOF is encountered and no characters were read into the array a null pointer is returned. In the fgets function in picolibc, it always returned NULL when it reaches EOF even if characters were read and that the file is not empty. Accordingly a flag was added that checks if the file is empty or not, there is an added "if" condition that checks on this flag, if EOF was encountered for whether NULL or the pointer to the array that was read will be returned. The case where it returns NULL occurs when EOF and no characters were read. This change checks and handles that fgets returns the pointer to the array correctly when it reaches EOF. --- newlib/libc/tinystdio/fgets.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/newlib/libc/tinystdio/fgets.c b/newlib/libc/tinystdio/fgets.c index 1a78b822e4..c589c30f2a 100644 --- a/newlib/libc/tinystdio/fgets.c +++ b/newlib/libc/tinystdio/fgets.c @@ -36,15 +36,21 @@ fgets(char *str, int size, FILE *stream) { char *cp; int c; + int empty_stream_flag = 0; //flag checks if stream is empty or not if ((stream->flags & __SRD) == 0 || size <= 0) return NULL; size--; for (c = 0, cp = str; c != '\n' && size > 0; size--, cp++) { - if ((c = getc(stream)) == EOF) - return NULL; + if ((c = getc(stream)) == EOF) { + if(empty_stream_flag == 0) + return NULL; + else + break; + } *cp = (char)c; + empty_stream_flag = 1; } *cp = '\0';