1//===-- Unittests for fopen / fclose --------------------------------------===//
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/__support/File/file.h"
10#include "src/stdio/fclose.h"
11#include "src/stdio/fopen.h"
12#include "src/stdio/fwrite.h"
13#include "src/stdio/fread.h"
14
15#include "test/UnitTest/Test.h"
16
17TEST(LlvmLibcFOpenTest, PrintToFile) {
18 int result;
19
20 FILE *file = LIBC_NAMESPACE::fopen(name: "./testdata/test_data.txt", mode: "w");
21 ASSERT_FALSE(file == nullptr);
22
23 static constexpr char STRING[] = "A simple string written to a file\n";
24 result = LIBC_NAMESPACE::fwrite(ptr: STRING, size: 1, nmemb: sizeof(STRING) - 1, stream: file);
25 EXPECT_GE(result, 0);
26
27 ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
28
29 FILE *new_file = LIBC_NAMESPACE::fopen(name: "./testdata/test_data.txt", mode: "r");
30 ASSERT_FALSE(new_file == nullptr);
31
32 static char data[64] = {0};
33 ASSERT_EQ(LIBC_NAMESPACE::fread(data, 1, sizeof(STRING) - 1, new_file),
34 sizeof(STRING) - 1);
35 data[sizeof(STRING) - 1] = '\0';
36 ASSERT_STREQ(data, STRING);
37
38 ASSERT_EQ(0, LIBC_NAMESPACE::fclose(new_file));
39}
40

source code of libc/test/src/stdio/fopen_test.cpp