From ccf8f404a8c77694b8d0f076152d8514d0750732 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 14 Oct 2022 19:36:20 +0200 Subject: [PATCH] libc: Make the stdio initialization code cleaner --- libs/libc/src/init.cpp | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/libs/libc/src/init.cpp b/libs/libc/src/init.cpp index 24df6f78..77e80d14 100644 --- a/libs/libc/src/init.cpp +++ b/libs/libc/src/init.cpp @@ -10,25 +10,22 @@ static void terminate_libc() fclose(stderr); } +static void check_for_file(int fd, FILE** target_stream, const char* path, const char* mode) +{ + if (lseek(fd, 0, SEEK_CUR) < 0) + { + if (errno == EBADF) *target_stream = fopen(path, mode); + else + exit(errno); + if (!*target_stream) exit(errno); + errno = 0; + } + else { *target_stream = fdopen(fd, mode); } +} + extern "C" void initialize_libc() { - if (lseek(0, 0, SEEK_CUR) < 0) - { - if (errno == EBADF) stdout = fopen("/dev/console", "rw"); - else - exit(errno); - if (!stdout) exit(errno); - errno = 0; - } - else { stdout = fdopen(0, "rw"); } - if (lseek(1, 0, SEEK_CUR) < 0) - { - if (errno == EBADF) stderr = fopen("/dev/console", "rw"); - else - exit(errno); - if (!stderr) exit(errno); - errno = 0; - } - else { stderr = fdopen(1, "rw"); } + check_for_file(0, &stdout, "/dev/console", "rw"); + check_for_file(1, &stderr, "/dev/console", "rw"); atexit(terminate_libc); } \ No newline at end of file