From acfad51ac0a592b57eabe976117ed51261a101ee Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 19 Jun 2023 10:46:08 +0200 Subject: [PATCH] libc: Add freopen() --- libc/include/stdio.h | 3 +++ libc/src/stdio.cpp | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/libc/include/stdio.h b/libc/include/stdio.h index fe3cc3ae..7596a9d9 100644 --- a/libc/include/stdio.h +++ b/libc/include/stdio.h @@ -41,6 +41,9 @@ extern "C" /* Bind a stream to a file descriptor. */ FILE* fdopen(int fd, const char* mode); + /* Change the underlying file and mode of a stream. */ + FILE* freopen(const char* path, const char* mode, FILE* stream); + /* Close a file and frees up its stream. */ int fclose(FILE* stream); diff --git a/libc/src/stdio.cpp b/libc/src/stdio.cpp index 16c509ad..bdcd82e4 100644 --- a/libc/src/stdio.cpp +++ b/libc/src/stdio.cpp @@ -85,6 +85,25 @@ extern "C" return f; } + FILE* freopen(const char* path, const char* mode, FILE* stream) + { + int flags; + + if ((flags = fopen_parse_mode(mode)) < 0) return nullptr; + + close(stream->_fd); + + if (!path) { fail("FIXME: freopen() called with path=nullptr"); } + + int fd = open(path, flags, 0666); + if (fd < 0) { return nullptr; } + + stream->_fd = fd; + clearerr(stream); + + return stream; + } + int fclose(FILE* stream) { if (close(stream->_fd) < 0) return EOF;