xref: /llvm-project/libc/test/src/stdio/fopen_test.cpp (revision b6bc9d72f65a5086f310f321e969d96e9a559e75)
1c850ea14SJoseph Huber //===-- Unittests for fopen / fclose --------------------------------------===//
2c850ea14SJoseph Huber //
3c850ea14SJoseph Huber // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4c850ea14SJoseph Huber // See https://llvm.org/LICENSE.txt for license information.
5c850ea14SJoseph Huber // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c850ea14SJoseph Huber //
7c850ea14SJoseph Huber //===----------------------------------------------------------------------===//
8c850ea14SJoseph Huber 
9c850ea14SJoseph Huber #include "src/__support/File/file.h"
10c850ea14SJoseph Huber #include "src/stdio/fclose.h"
11c850ea14SJoseph Huber #include "src/stdio/fopen.h"
1260c0d303SJoseph Huber #include "src/stdio/fwrite.h"
13334bbc0dSJoseph Huber #include "src/stdio/fread.h"
14c850ea14SJoseph Huber 
15c850ea14SJoseph Huber #include "test/UnitTest/Test.h"
16c850ea14SJoseph Huber 
TEST(LlvmLibcFOpenTest,PrintToFile)17c850ea14SJoseph Huber TEST(LlvmLibcFOpenTest, PrintToFile) {
18c850ea14SJoseph Huber   int result;
19c850ea14SJoseph Huber 
20*b6bc9d72SGuillaume Chatelet   FILE *file = LIBC_NAMESPACE::fopen("./testdata/test_data.txt", "w");
21c850ea14SJoseph Huber   ASSERT_FALSE(file == nullptr);
22c850ea14SJoseph Huber 
23334bbc0dSJoseph Huber   static constexpr char STRING[] = "A simple string written to a file\n";
24*b6bc9d72SGuillaume Chatelet   result = LIBC_NAMESPACE::fwrite(STRING, 1, sizeof(STRING) - 1, file);
25c850ea14SJoseph Huber   EXPECT_GE(result, 0);
26c850ea14SJoseph Huber 
27*b6bc9d72SGuillaume Chatelet   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
28334bbc0dSJoseph Huber 
29*b6bc9d72SGuillaume Chatelet   FILE *new_file = LIBC_NAMESPACE::fopen("./testdata/test_data.txt", "r");
30334bbc0dSJoseph Huber   ASSERT_FALSE(new_file == nullptr);
31334bbc0dSJoseph Huber 
32334bbc0dSJoseph Huber   static char data[64] = {0};
33*b6bc9d72SGuillaume Chatelet   ASSERT_EQ(LIBC_NAMESPACE::fread(data, 1, sizeof(STRING) - 1, new_file),
34334bbc0dSJoseph Huber             sizeof(STRING) - 1);
35334bbc0dSJoseph Huber   data[sizeof(STRING) - 1] = '\0';
36334bbc0dSJoseph Huber   ASSERT_STREQ(data, STRING);
37334bbc0dSJoseph Huber 
38*b6bc9d72SGuillaume Chatelet   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(new_file));
39c850ea14SJoseph Huber }
40