1//===-- Unittests for fprintf ---------------------------------------------===//
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#ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
10#include "src/stdio/fclose.h"
11#include "src/stdio/ferror.h"
12#include "src/stdio/fopen.h"
13#include "src/stdio/fread.h"
14#endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
15
16#include "src/stdio/fprintf.h"
17
18#include "test/UnitTest/Test.h"
19
20#include <stdio.h>
21
22namespace printf_test {
23#ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
24using LIBC_NAMESPACE::fclose;
25using LIBC_NAMESPACE::ferror;
26using LIBC_NAMESPACE::fopen;
27using LIBC_NAMESPACE::fread;
28#else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
29using ::fclose;
30using ::ferror;
31using ::fopen;
32using ::fread;
33#endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
34} // namespace printf_test
35
36TEST(LlvmLibcFPrintfTest, WriteToFile) {
37 const char *FILENAME = "fprintf_output.test";
38 auto FILE_PATH = libc_make_test_file_path(FILENAME);
39
40 ::FILE *file = printf_test::fopen(filename: FILE_PATH, modes: "w");
41 ASSERT_FALSE(file == nullptr);
42
43 int written;
44
45 constexpr char simple[] = "A simple string with no conversions.\n";
46 written = LIBC_NAMESPACE::fprintf(stream: file, format: simple);
47 EXPECT_EQ(written, 37);
48
49 constexpr char numbers[] = "1234567890\n";
50 written = LIBC_NAMESPACE::fprintf(stream: file, format: "%s", numbers);
51 EXPECT_EQ(written, 11);
52
53 constexpr char format_more[] = "%s and more\n";
54 constexpr char short_numbers[] = "1234";
55 written = LIBC_NAMESPACE::fprintf(stream: file, format: format_more, short_numbers);
56 EXPECT_EQ(written, 14);
57
58 ASSERT_EQ(0, printf_test::fclose(file));
59
60 file = printf_test::fopen(filename: FILE_PATH, modes: "r");
61 ASSERT_FALSE(file == nullptr);
62
63 char data[50];
64 ASSERT_EQ(printf_test::fread(data, 1, sizeof(simple) - 1, file),
65 sizeof(simple) - 1);
66 data[sizeof(simple) - 1] = '\0';
67 ASSERT_STREQ(data, simple);
68 ASSERT_EQ(printf_test::fread(data, 1, sizeof(numbers) - 1, file),
69 sizeof(numbers) - 1);
70 data[sizeof(numbers) - 1] = '\0';
71 ASSERT_STREQ(data, numbers);
72 ASSERT_EQ(printf_test::fread(
73 data, 1, sizeof(format_more) + sizeof(short_numbers) - 4, file),
74 sizeof(format_more) + sizeof(short_numbers) - 4);
75 data[sizeof(format_more) + sizeof(short_numbers) - 4] = '\0';
76 ASSERT_STREQ(data, "1234 and more\n");
77
78 ASSERT_EQ(printf_test::ferror(file), 0);
79
80 written =
81 LIBC_NAMESPACE::fprintf(stream: file, format: "Writing to a read only file should fail.");
82 EXPECT_LT(written, 0);
83
84 ASSERT_EQ(printf_test::fclose(file), 0);
85}
86

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