[libc-commits] [libc] [libc] Ignore unknown characters after the fopen mode (PR #236968)

Mike Lothian via libc-commits libc-commits at lists.llvm.org
Fri Oct 30 01:25:08 PDT 2026


https://github.com/FireBurn updated https://github.com/llvm/llvm-project/pull/236968

>From 8899091d3887dec2e80680d6609eaa014120ce65 Mon Sep 17 00:00:00 2001
From: Mike Lothian <mike at fireburn.co.uk>
Date: Sat, 10 Oct 2026 04:32:40 +0100
Subject: [PATCH] [libc] Ignore unknown characters after the fopen mode

glibc and musl ignore mode characters they do not know, so programs such
as sed that open files with "rt" work on them. FileMode treated any
unknown character as an invalid mode.

Assisted-by: Claude
---
 libc/src/__support/File/file_mode.h           |  4 +++-
 .../src/__support/File/file_mode_test.cpp     | 20 +++++++++++++++++--
 2 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/libc/src/__support/File/file_mode.h b/libc/src/__support/File/file_mode.h
index 1c4c8b7b7e3986..8d94734a60c648 100644
--- a/libc/src/__support/File/file_mode.h
+++ b/libc/src/__support/File/file_mode.h
@@ -66,7 +66,9 @@ class FileMode {
         file_mode_ |= static_cast<Mode>(Extension::CLOSE_ON_EXEC);
         break;
       default:
-        file_mode_ = 0;
+        // Like glibc and musl, ignore characters we do not know, such as the
+        // 't' in "rt".
+        break;
       }
     }
 
diff --git a/libc/test/src/__support/File/file_mode_test.cpp b/libc/test/src/__support/File/file_mode_test.cpp
index 6048b49c8b27a5..e062221b65aab1 100644
--- a/libc/test/src/__support/File/file_mode_test.cpp
+++ b/libc/test/src/__support/File/file_mode_test.cpp
@@ -6,8 +6,8 @@
 //
 //===----------------------------------------------------------------------===//
 ///
-/// file_mode_test.cpp
-/// This file contains possible test cases for FileMode class.
+/// \file
+/// Test cases for the FileMode class.
 ///
 //===----------------------------------------------------------------------===//
 
@@ -230,6 +230,22 @@ TEST(LlvmLibcFileModeTest, CloseOnExecCombinations) {
   EXPECT_TRUE(write_all_modifiers.write_allowed());
 }
 
+TEST(LlvmLibcFileModeTest, UnknownCharactersAreIgnored) {
+  constexpr FileMode read_text("rt");
+  EXPECT_TRUE(read_text.is_valid());
+  EXPECT_TRUE(read_text.is_read());
+  EXPECT_FALSE(read_text.is_binary_format());
+
+  constexpr FileMode write_unknown("wzb");
+  EXPECT_TRUE(write_unknown.is_valid());
+  EXPECT_TRUE(write_unknown.is_write());
+  EXPECT_TRUE(write_unknown.is_binary_format());
+
+  // The first character must still be a main mode.
+  constexpr FileMode text_first("tr");
+  EXPECT_FALSE(text_first.is_valid());
+}
+
 TEST(LlvmLibcFileModeTest, InvalidCombinations) {
   // 1. Read and Write as main modes
   constexpr FileMode read_and_write("rw");



More information about the libc-commits mailing list