From de6041fedef397a1843706ee7af43f9ef8ad7b71 Mon Sep 17 00:00:00 2001 From: apio Date: Wed, 12 Oct 2022 20:19:13 +0200 Subject: [PATCH] libc: Add fdopen() --- libs/libc/include/stdio.h | 3 +++ libs/libc/src/file.cpp | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/libs/libc/include/stdio.h b/libs/libc/include/stdio.h index 0173caac..b0e0aab9 100644 --- a/libs/libc/include/stdio.h +++ b/libs/libc/include/stdio.h @@ -32,6 +32,9 @@ extern "C" /* Opens the file specified by pathname. Returns the file handle on success, or NULL on error. */ FILE* fopen(const char* pathname, const char* mode); + /* Returns a new file associated with the file descriptor fd. */ + FILE* fdopen(int fd, const char* mode); + /* Writes formatted output according to the string format to the file stream. */ int fprintf(FILE* stream, const char* format, ...); diff --git a/libs/libc/src/file.cpp b/libs/libc/src/file.cpp index 2aade1dd..e0525a22 100644 --- a/libs/libc/src/file.cpp +++ b/libs/libc/src/file.cpp @@ -40,6 +40,19 @@ extern "C" return stream; } + FILE* fdopen(int fd, const char*) + { + if (fd < 0) // FIXME: Also check if the mode string is compatible with how fd was opened. + { + errno = EBADF; + return 0; + } + FILE* stream = (FILE*)malloc(sizeof(FILE)); + stream->f_fd = fd; + clearerr(stream); + return stream; + } + size_t fread(void* buf, size_t size, size_t nmemb, FILE* stream) { ssize_t status = read(stream->f_fd, buf, size * nmemb);