[libc-commits] [libc] [libc] implement rewind (PR #191302)

Alexey Samsonov via libc-commits libc-commits at lists.llvm.org
Thu Apr 9 15:42:41 PDT 2026


================
@@ -0,0 +1,77 @@
+//===-- Unittests for file operations like fopen, flcose etc --------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/stdio/fclose.h"
+#include "src/stdio/ferror.h"
+#include "src/stdio/fopen.h"
+#include "src/stdio/fread.h"
+#include "src/stdio/fwrite.h"
+#include "src/stdio/rewind.h"
+#include "test/UnitTest/ErrnoCheckingTest.h"
+#include "test/UnitTest/ErrnoSetterMatcher.h"
+#include "test/UnitTest/Test.h"
+
+using LlvmLibcRewindTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::EQ;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::NE;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::returns;
+
+TEST_F(LlvmLibcRewindTest, WriteRewindRead) {
+  constexpr char FILENAME[] = APPEND_LIBC_TEST("testdata/rewind.test");
+  auto FILEPATH = libc_make_test_file_path(FILENAME);
+  ::FILE *file = LIBC_NAMESPACE::fopen(FILEPATH, "w");
+  ASSERT_FALSE(file == nullptr);
+
+  constexpr char FIRST_DATA[] = "123456789";
+  ASSERT_THAT(LIBC_NAMESPACE::fwrite(FIRST_DATA, 1, sizeof(FIRST_DATA), file),
+              returns(EQ(sizeof(FIRST_DATA))).with_errno(EQ(0)));
+
+  // File state is "123456789"
+
+  LIBC_NAMESPACE::rewind(file);
+
+  // Cursor is back to the start
+
+  constexpr char SECOND_DATA[] = "abc";
+  ASSERT_THAT(
+      LIBC_NAMESPACE::fwrite(SECOND_DATA, 1, sizeof(SECOND_DATA) - 1, file),
+      returns(EQ(sizeof(SECOND_DATA) - 1)).with_errno(EQ(0)));
+
+  // File state is "abc456789"
+
+  // attempt to read from write-only file causing error state
+  char read_data[sizeof(FIRST_DATA)];
+  ASSERT_THAT(LIBC_NAMESPACE::fread(read_data, 1, sizeof(read_data), file),
+              returns(EQ(size_t(0))).with_errno(NE(0)));
----------------
vonosmas wrote:

If we really can't tell which errno is expected, we can also express it as:
```
ASSERT_EQ(LIBC_NAMESPACE::fread(read_data, 1, sizeof(read_data), file), size_t(0));
ASSERT_ERRNO_FAILURE();
```

https://github.com/llvm/llvm-project/pull/191302


More information about the libc-commits mailing list