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/fopen.h"
11 #include "src/stdio/fread.h"
12 #include "src/stdio/fseek.h"
13 #include "src/stdio/fwrite.h"
14 #include "utils/UnitTest/Test.h"
15 
16 #include <stdio.h>
17 
18 TEST(LlvmLibcStdio, SimpleOperations) {
19   constexpr char FILENAME[] = "testdata/simple_operations.test";
20   ::FILE *file = __llvm_libc::fopen(FILENAME, "w");
21   ASSERT_FALSE(file == nullptr);
22   constexpr char CONTENT[] = "1234567890987654321";
23   ASSERT_EQ(sizeof(CONTENT) - 1,
24             __llvm_libc::fwrite(CONTENT, 1, sizeof(CONTENT) - 1, file));
25   ASSERT_EQ(0, __llvm_libc::fclose(file));
26 
27   file = __llvm_libc::fopen(FILENAME, "r");
28   ASSERT_FALSE(file == nullptr);
29 
30   constexpr size_t READ_SIZE = 5;
31   char data[READ_SIZE];
32   data[READ_SIZE - 1] = '\0';
33   ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1);
34   ASSERT_STREQ(data, "1234");
35   ASSERT_EQ(__llvm_libc::fseek(file, 5, SEEK_CUR), 0);
36   ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1);
37   ASSERT_STREQ(data, "0987");
38   ASSERT_EQ(__llvm_libc::fseek(file, -5, SEEK_CUR), 0);
39   ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1);
40   ASSERT_STREQ(data, "9098");
41 
42   ASSERT_EQ(__llvm_libc::fclose(file), 0);
43 }
44