From 9e9f268562195d747cdeb7fcc6ad7f88c56db27d Mon Sep 17 00:00:00 2001 From: apio Date: Sun, 12 Mar 2023 17:36:04 +0100 Subject: [PATCH] libc: Make fopen() parse the mode string --- libc/src/stdio.cpp | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/libc/src/stdio.cpp b/libc/src/stdio.cpp index be4210f1..e34f59d0 100644 --- a/libc/src/stdio.cpp +++ b/libc/src/stdio.cpp @@ -10,6 +10,23 @@ FILE* stderr = nullptr; +static int fopen_parse_mode(const char* mode) +{ + int result = 0; + switch (*mode) + { + case 'r': result |= O_RDONLY; break; + case 'w': result |= (O_WRONLY | O_CREAT | O_TRUNC); break; + case 'a': result |= (O_WRONLY | O_CREAT | O_APPEND); break; + + default: errno = EINVAL; return -1; + } + + if (strchr(mode, '+')) result |= O_RDWR; + + return result; +} + extern "C" { int console_write(const char* str, size_t size) @@ -18,10 +35,13 @@ extern "C" __errno_return(rc, int); } - FILE* fopen(const char* path, const char*) + FILE* fopen(const char* path, const char* mode) { - // FIXME: Parse the mode string. - int fd = open(path, O_RDWR); + int flags; + + if ((flags = fopen_parse_mode(mode)) < 0) return nullptr; + + int fd = open(path, flags, 0666); if (fd < 0) return nullptr; FILE* f = (FILE*)malloc(sizeof(FILE));