From b2f321c0b832245a9a8a89abbc79a0001f8ba1c2 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 28 Oct 2022 17:02:08 +0200 Subject: [PATCH] libc: Parse the mode string --- libs/libc/src/file.cpp | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/libs/libc/src/file.cpp b/libs/libc/src/file.cpp index af14e3fc..77b5c9c6 100644 --- a/libs/libc/src/file.cpp +++ b/libs/libc/src/file.cpp @@ -3,13 +3,14 @@ #include #include #include +#include #include FILE* stderr; FILE* stdout; FILE* stdin; -void file_read_buf(FILE* stream) +static void file_read_buf(FILE* stream) { if (!stream->f_buf) { @@ -31,6 +32,29 @@ void file_read_buf(FILE* stream) stream->f_bufsize = nread; } +static int file_parse_mode(const char* mode) +{ + int flags = 0; + switch (mode[0]) + { + case 'r': flags |= O_RDONLY; break; + case 'w': + flags |= O_WRONLY; + flags |= O_CREAT; + flags |= O_TRUNC; + break; + case 'a': + flags |= O_WRONLY; + flags |= O_CREAT; + flags |= O_APPEND; + break; + default: errno = EINVAL; return -1; + } + + if (strchr(mode, '+')) flags |= O_RDWR; + return flags; +} + extern "C" { int fclose(FILE* stream) @@ -56,7 +80,9 @@ extern "C" FILE* fopen(const char* pathname, const char* mode) { - int fd = open(pathname, O_RDWR); // FIXME: Use the mode string. + int flags = file_parse_mode(mode); + if (flags < 0) return NULL; + int fd = open(pathname, flags, 0666); // If we create the file, create it as rw-rw-rw-. if (fd < 0) { return 0; } return fdopen(fd, mode); } @@ -78,10 +104,12 @@ extern "C" return stream; } - FILE* freopen(const char* pathname, const char*, + FILE* freopen(const char* pathname, const char* mode, FILE* stream) // FIXME: If pathname is NULL, open the original file with the new mode. { - int fd = open(pathname, O_RDWR); // FIXME: Use the mode string. + int flags = file_parse_mode(mode); + if (flags < 0) return NULL; + int fd = open(pathname, flags, 0666); // If we create the file, create it as rw-rw-rw-. if (fd < 0) { return 0; } fflush(stream); // To make it future-proof.