From 894065a67eef9f0ed9dccdee4112cf51dc9408a5 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Tue, 5 Dec 2023 10:00:43 +0200 Subject: [PATCH] LibC: cleanup and fix fgets My quick fix for fgets wrote non-nullterminated newline if size was one. POSIX doesn't specify what happens if size == 0, so I do the same as glibc and return NULL without setting errno. --- libc/stdio.cpp | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/libc/stdio.cpp b/libc/stdio.cpp index 0df704bf90..54f22045b1 100644 --- a/libc/stdio.cpp +++ b/libc/stdio.cpp @@ -135,37 +135,26 @@ int fgetpos(FILE* file, fpos_t* pos) char* fgets(char* str, int size, FILE* file) { - if (size == 1) - str[0] = '\n'; - if (size <= 1) - return str; - - int c = fgetc(file); - if (c == EOF) + if (size == 0) return nullptr; - str[0] = c; - if (str[0] == '\n') + int i = 0; + for (; i < size - 1; i++) { - str[1] = '\0'; - return str; - } - - for (int i = 1; i < size - 1; i++) - { - str[i] = fgetc(file); - if (str[i] == EOF) + char c = fgetc(file); + if (c == EOF) { - str[i] = '\0'; - return str; + if (i == 0) + return nullptr; + break; } - if (str[i] == '\n') + str[i] = c; + if (c == '\n') { - str[i + 1] = '\0'; - return str; + i++; + break; } } - - str[size - 1] = '\0'; + str[i] = '\0'; return str; }