From 9928088868f74d2d5873610c71cf922338a9db8a Mon Sep 17 00:00:00 2001 From: Xiang Xiao Date: Thu, 15 Oct 2020 21:39:10 +0800 Subject: [PATCH] libc: Don't fclose and fopen file in freopen to avoid FILE pointer change after this commit: commit b0797263ca2817cf536be8b843ac5b5aac5d4d9c Author: Xiang Xiao Date: Thu Aug 13 18:17:29 2020 +0800 libc/stdio: Allocate file_struct dynamically 1.Reduce the default size of task_group_s(~512B each task) 2.Scale better between simple and complex application Signed-off-by: Xiang Xiao --- libs/libc/stdio/lib_freopen.c | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/libs/libc/stdio/lib_freopen.c b/libs/libc/stdio/lib_freopen.c index 7f1081f3ca..eff42fd372 100644 --- a/libs/libc/stdio/lib_freopen.c +++ b/libs/libc/stdio/lib_freopen.c @@ -94,16 +94,39 @@ FAR FILE *freopen(FAR const char *path, FAR const char *mode, if (path != NULL) { - /* Yes, close the stream */ + /* Yes, open the file directly if no stream is opened yet */ - if (stream) + if (stream == NULL) { - fclose(stream); + return fopen(path, mode); } - /* And attempt to reopen the file at the provided path */ + /* Otherwise, open the file */ - return fopen(path, mode); + oflags = lib_mode2oflags(mode); + if (oflags < 0) + { + return NULL; + } + + fd = open(path, oflags, 0666); + if (fd < 0) + { + return NULL; + } + + /* Flush the stream and duplicate the new fd to it */ + + fflush(stream); + ret = dup2(fd, fileno(stream)); + close(fd); + if (ret < 0) + { + return NULL; + } + + clearerr(stream); + return stream; } /* Otherwise, we are just changing the mode of the current file. */