From 0e9890901f5e9ee11d92a212c93548fc0fa6cfa5 Mon Sep 17 00:00:00 2001 From: apio Date: Thu, 23 Mar 2023 21:35:09 +0100 Subject: [PATCH] libc: Add (f)getc, getchar, and fgets --- libc/include/stdio.h | 12 ++++++++++++ libc/src/stdio.cpp | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/libc/include/stdio.h b/libc/include/stdio.h index acf3643c..e5b49797 100644 --- a/libc/include/stdio.h +++ b/libc/include/stdio.h @@ -81,6 +81,18 @@ extern "C" /* Write a string to stream. */ int fputs(const char* str, FILE* stream); + /* Read a character from stream. */ + int fgetc(FILE* stream); + + /* Read a character from stream. */ + int getc(FILE* stream); + + /* Read a character from standard input. */ + int getchar(); + + /* Read a line from stream. */ + char* fgets(char* buf, size_t size, FILE* stream); + /* Clear the error and end-of-file indicators in stream. */ void clearerr(FILE* stream); diff --git a/libc/src/stdio.cpp b/libc/src/stdio.cpp index d18bb112..bc5cc32e 100644 --- a/libc/src/stdio.cpp +++ b/libc/src/stdio.cpp @@ -187,6 +187,42 @@ extern "C" return (rc < 0) ? -1 : 0; } + int fgetc(FILE* stream) + { + u8 value; + ssize_t rc = read(stream->_fd, &value, 1); + if (rc <= 0) return EOF; + return value; + } + + int getc(FILE* stream) + { + return fgetc(stream); + } + + int getchar() + { + return fgetc(stdin); + } + + char* fgets(char* buf, size_t size, FILE* stream) + { + size_t i = 0; + while (i + 1 < size) + { + int c = fgetc(stream); + if (c == EOF) break; + buf[i++] = (char)c; + if (c == '\n') break; + } + + if (i == 0) return NULL; + + buf[i] = 0; + + return buf; + } + void clearerr(FILE* stream) { stream->_eof = stream->_err = 0;