From 469a10ef344f34553b62fe6a48b4fd9f7bc7da85 Mon Sep 17 00:00:00 2001 From: julianuziemblo Date: Fri, 8 May 2026 10:44:41 +0200 Subject: [PATCH] stdio: fix fgets(), add gets() Fixes: phoenix-rtos/phoenix-rtos-project#1489 --- posix/stubs.c | 5 ----- stdio/file.c | 58 +++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/posix/stubs.c b/posix/stubs.c index 8c23d239..fdf3a4fe 100644 --- a/posix/stubs.c +++ b/posix/stubs.c @@ -194,11 +194,6 @@ long ulimit(int __cmd, ...) return 0; } -char *gets(char *str) -{ - return NULL; -} - char *tmpnam(char *str) { return NULL; diff --git a/stdio/file.c b/stdio/file.c index c54d207c..1457a0c4 100644 --- a/stdio/file.c +++ b/stdio/file.c @@ -734,21 +734,36 @@ int fputc(int c, FILE *stream) char *fgets_unlocked(char *str, int n, FILE *stream) { + if (n < 1) { + return NULL; + } + + if (n == 1) { + str[0] = '\0'; + return str; + } + int c, i = 0; - while ((c = fgetc_unlocked(stream)) != EOF) { - str[i++] = c; - if (c == '\n' || i == n - 1) { + + while (i < n - 1) { + c = getc_unlocked(stream); + if (c == EOF) { + if (i == 0) { + return NULL; + } break; } - } - if (i) { - str[i] = 0; - } - else { - return NULL; + str[i] = c; + i++; + + if (c == '\n') { + break; + } } + str[i] = '\0'; + return str; } @@ -938,6 +953,31 @@ int getc_unlocked(FILE *stream) } +char *gets(char *str) +{ + int c; + char *ret; + mutexLock(stdin->lock); + c = getc_unlocked(stdin); + if (c == EOF) { + ret = NULL; + } + else { + ret = str; + do { + if (c == '\n') { + break; + } + *str = c; + str++; + } while ((c = getc_unlocked(stdin)) != EOF); + *str = '\0'; + } + mutexUnlock(stdin->lock); + return ret; +} + + int getc(FILE *stream) { int ret;