1 //===-- Unittests for fprintf ---------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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
16 #include "src/stdio/fprintf.h"
18 #include "test/UnitTest/Test.h"
22 namespace printf_test
{
23 #ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
24 using LIBC_NAMESPACE::fclose
;
25 using LIBC_NAMESPACE::ferror
;
26 using LIBC_NAMESPACE::fopen
;
27 using LIBC_NAMESPACE::fread
;
28 #else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
33 #endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
34 } // namespace printf_test
36 TEST(LlvmLibcFPrintfTest
, WriteToFile
) {
37 const char *FILENAME
= "fprintf_output.test";
38 auto FILE_PATH
= libc_make_test_file_path(FILENAME
);
40 ::FILE *file
= printf_test::fopen(FILE_PATH
, "w");
41 ASSERT_FALSE(file
== nullptr);
45 constexpr char simple
[] = "A simple string with no conversions.\n";
46 written
= LIBC_NAMESPACE::fprintf(file
, simple
);
47 EXPECT_EQ(written
, 37);
49 constexpr char numbers
[] = "1234567890\n";
50 written
= LIBC_NAMESPACE::fprintf(file
, "%s", numbers
);
51 EXPECT_EQ(written
, 11);
53 constexpr char format_more
[] = "%s and more\n";
54 constexpr char short_numbers
[] = "1234";
55 written
= LIBC_NAMESPACE::fprintf(file
, format_more
, short_numbers
);
56 EXPECT_EQ(written
, 14);
58 ASSERT_EQ(0, printf_test::fclose(file
));
60 file
= printf_test::fopen(FILE_PATH
, "r");
61 ASSERT_FALSE(file
== nullptr);
64 ASSERT_EQ(printf_test::fread(data
, 1, sizeof(simple
) - 1, file
),
66 data
[sizeof(simple
) - 1] = '\0';
67 ASSERT_STREQ(data
, simple
);
68 ASSERT_EQ(printf_test::fread(data
, 1, sizeof(numbers
) - 1, file
),
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");
78 ASSERT_EQ(printf_test::ferror(file
), 0);
81 LIBC_NAMESPACE::fprintf(file
, "Writing to a read only file should fail.");
82 EXPECT_LT(written
, 0);
84 ASSERT_EQ(printf_test::fclose(file
), 0);