[libc-commits] [libc] [libc] Add the implementation of the fdopen function (PR #94186)
Michael Jones via libc-commits
libc-commits at lists.llvm.org
Fri Jun 7 11:10:15 PDT 2024
================
@@ -0,0 +1,90 @@
+//===-- Unittest for fdopen -----------------------------------------------===//
+//
+// 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/fdopen.h"
+
+#include "include/llvm-libc-macros/fcntl-macros.h"
+#include "src/errno/libc_errno.h"
+#include "src/fcntl/open.h"
+#include "src/stdio/fclose.h"
+#include "src/stdio/fgets.h"
+#include "src/stdio/fputs.h"
+#include "src/unistd/close.h"
+#include "test/UnitTest/ErrnoSetterMatcher.h"
+#include "test/UnitTest/Test.h"
+
+#include <sys/stat.h> // For S_IRWXU
+
+TEST(LlvmLibcStdioFdopenTest, WriteAppendRead) {
+ using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
+ LIBC_NAMESPACE::libc_errno = 0;
+ constexpr const char *TEST_FILE_NAME = "testdata/write_read_append.test";
+ auto TEST_FILE = libc_make_test_file_path(TEST_FILE_NAME);
+ int fd = LIBC_NAMESPACE::open(TEST_FILE, O_CREAT | O_TRUNC | O_RDWR, S_IRWXU);
+ auto *fp = LIBC_NAMESPACE::fdopen(fd, "w");
+ ASSERT_ERRNO_SUCCESS();
+ ASSERT_TRUE(nullptr != fp);
+ constexpr const char HELLO[] = "Hello";
+ LIBC_NAMESPACE::fputs(HELLO, fp);
+ LIBC_NAMESPACE::fclose(fp);
+ ASSERT_ERRNO_SUCCESS();
+
+ constexpr const char LLVM[] = "LLVM";
+ int fd2 = LIBC_NAMESPACE::open(TEST_FILE, O_CREAT | O_RDWR);
+ auto *fp2 = LIBC_NAMESPACE::fdopen(fd2, "a");
+ ASSERT_ERRNO_SUCCESS();
+ ASSERT_TRUE(nullptr != fp2);
+ LIBC_NAMESPACE::fputs(LLVM, fp2);
+ LIBC_NAMESPACE::fclose(fp2);
+ ASSERT_ERRNO_SUCCESS();
+
+ int fd3 = LIBC_NAMESPACE::open(TEST_FILE, O_CREAT | O_RDWR);
+ auto *fp3 = LIBC_NAMESPACE::fdopen(fd3, "r");
+ char buffer[10];
+ LIBC_NAMESPACE::fgets(buffer, sizeof(buffer), fp3);
+ EXPECT_EQ('H', buffer[0]);
----------------
michaelrj-google wrote:
instead of checking just two characters you can use `ASSERT_STREQ` to check the whole string at once. You might need to make sure that `buffer` has a null byte at the end for that.
https://github.com/llvm/llvm-project/pull/94186
More information about the libc-commits
mailing list