Skip to content

Commit

Permalink
tinystdio: fgets returns NULL only when EOF is reached
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
HanaMAshour authored Apr 18, 2024
1 parent 9adab07 commit 40a093b
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions newlib/libc/tinystdio/fgets.c
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down

0 comments on commit 40a093b

Please sign in to comment.