This is an automated email from the ASF dual-hosted git repository.

GUIDINGLI pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit c5dd83fe3bbf7e987041b3c904f075ab39fba36d
Author: anpeiyun <[email protected]>
AuthorDate: Wed Sep 17 10:40:56 2025 +0800

    libc/stdio: Update the stream mode in freopen() when pathname is NULL.
    
    According to POSIX, when pathname is a null pointer, freopen() shall
    attempt to change the mode of the stream to that specified by mode, as
    if using the name of the file currently associated with the stream.
    The file descriptor got the new mode, but the stream kept the old one.
    
    POSIX also requires freopen() to first flush the stream as if by
    fflush(stream).  This branch did not, so once the stream had the new
    mode, data still buffered for writing was dropped when a write stream
    was reopened as "r".  Flush it before the mode changes.
    
    https://pubs.opengroup.org/onlinepubs/9699919799/functions/freopen.html
    
    Signed-off-by: anpeiyun <[email protected]>
    Signed-off-by: ganjing <[email protected]>
---
 libs/libc/stdio/lib_freopen.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/libs/libc/stdio/lib_freopen.c b/libs/libc/stdio/lib_freopen.c
index c9096589b99..7a92fc84195 100644
--- a/libs/libc/stdio/lib_freopen.c
+++ b/libs/libc/stdio/lib_freopen.c
@@ -184,6 +184,13 @@ FAR FILE *freopen(FAR const char *path, FAR const char 
*mode,
           return NULL;
         }
 
+      /* Write out buffered data before the mode changes, as POSIX
+       * requires, so that it is not dropped when the stream is no longer
+       * writable.
+       */
+
+      lib_fflush(stream);
+
       /* Set the new file mode for the file descriptor */
 
       ret = fcntl(fd, F_SETFL, oflags);
@@ -192,6 +199,10 @@ FAR FILE *freopen(FAR const char *path, FAR const char 
*mode,
           return NULL;
         }
 
+      /* Set the new file mode for the file stream */
+
+      stream->fs_oflags = oflags;
+
       clearerr(stream);
       return stream;
     }

Reply via email to