libc: Add (f)getc, getchar, and fgets

This commit is contained in:
apio 2023-03-23 21:35:09 +01:00
parent 937802964c
commit 0e9890901f
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 48 additions and 0 deletions

View File

@ -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);

View File

@ -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;