From 95fc8943032e3fb449b9fe57316bba51faf997b2 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Tue, 5 Dec 2023 07:46:14 +0200 Subject: [PATCH] LibC: fix fgets when reading empty line --- libc/stdio.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/libc/stdio.cpp b/libc/stdio.cpp index d05273d0a7..0df704bf90 100644 --- a/libc/stdio.cpp +++ b/libc/stdio.cpp @@ -135,19 +135,28 @@ int fgetpos(FILE* file, fpos_t* pos) char* fgets(char* str, int size, FILE* file) { - if (size == 0) + if (size == 1) + str[0] = '\n'; + if (size <= 1) return str; + int c = fgetc(file); if (c == EOF) return nullptr; str[0] = c; + if (str[0] == '\n') + { + str[1] = '\0'; + return str; + } + for (int i = 1; i < size - 1; i++) { str[i] = fgetc(file); if (str[i] == EOF) { str[i] = '\0'; - return nullptr; + return str; } if (str[i] == '\n') { @@ -155,6 +164,7 @@ char* fgets(char* str, int size, FILE* file) return str; } } + str[size - 1] = '\0'; return str; }