1 //===-- Unittests for file operations like fopen, flcose etc --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/stdio/fclose.h"
10 #include "src/stdio/flockfile.h"
11 #include "src/stdio/fopen.h"
12 #include "src/stdio/fread_unlocked.h"
13 #include "src/stdio/funlockfile.h"
14 #include "src/stdio/fwrite_unlocked.h"
15 #include "utils/UnitTest/Test.h"
16 
17 #include <stdio.h>
18 
19 TEST(LlvmLibcFILETest, UnlockedReadAndWrite) {
20   constexpr char FILENAME[] = "testdata/unlocked_read_and_write.test";
21   ::FILE *file = __llvm_libc::fopen(FILENAME, "w");
22   ASSERT_FALSE(file == nullptr);
23   constexpr char CONTENT[] = "1234567890987654321";
24   __llvm_libc::flockfile(file);
25   ASSERT_EQ(sizeof(CONTENT) - 1, __llvm_libc::fwrite_unlocked(
26                                      CONTENT, 1, sizeof(CONTENT) - 1, file));
27   __llvm_libc::funlockfile(file);
28   ASSERT_EQ(0, __llvm_libc::fclose(file));
29 
30   file = __llvm_libc::fopen(FILENAME, "r");
31   ASSERT_FALSE(file == nullptr);
32 
33   constexpr size_t READ_SIZE = 5;
34   char data[READ_SIZE * 2 + 1];
35   data[READ_SIZE * 2] = '\0';
36   __llvm_libc::flockfile(file);
37   ASSERT_EQ(__llvm_libc::fread_unlocked(data, 1, READ_SIZE, file), READ_SIZE);
38   ASSERT_EQ(__llvm_libc::fread_unlocked(data + READ_SIZE, 1, READ_SIZE, file),
39             READ_SIZE);
40   __llvm_libc::funlockfile(file);
41   ASSERT_STREQ(data, "1234567890");
42 
43   ASSERT_EQ(__llvm_libc::fclose(file), 0);
44 }
45