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 #include "src/stdio/fclose.h"
10 #include "src/stdio/ferror.h"
11 #include "src/stdio/fopen.h"
12 #include "src/stdio/fread.h"
14 #include "src/stdio/fprintf.h"
16 #include "test/UnitTest/Test.h"
21 TEST(LlvmLibcFPrintfTest
, WriteToFile
) {
22 constexpr char FILENAME
[] = "testdata/fprintf_output.test";
23 ::FILE *file
= __llvm_libc::fopen(FILENAME
, "w");
24 ASSERT_FALSE(file
== nullptr);
28 constexpr char simple
[] = "A simple string with no conversions.\n";
29 written
= __llvm_libc::fprintf(file
, simple
);
30 EXPECT_EQ(written
, 37);
32 constexpr char numbers
[] = "1234567890\n";
33 written
= __llvm_libc::fprintf(file
, "%s", numbers
);
34 EXPECT_EQ(written
, 11);
36 constexpr char format_more
[] = "%s and more\n";
37 constexpr char short_numbers
[] = "1234";
38 written
= __llvm_libc::fprintf(file
, format_more
, short_numbers
);
39 EXPECT_EQ(written
, 14);
41 ASSERT_EQ(0, __llvm_libc::fclose(file
));
43 file
= __llvm_libc::fopen(FILENAME
, "r");
44 ASSERT_FALSE(file
== nullptr);
47 ASSERT_EQ(__llvm_libc::fread(data
, 1, sizeof(simple
) - 1, file
),
49 data
[sizeof(simple
) - 1] = '\0';
50 ASSERT_STREQ(data
, simple
);
51 ASSERT_EQ(__llvm_libc::fread(data
, 1, sizeof(numbers
) - 1, file
),
53 data
[sizeof(numbers
) - 1] = '\0';
54 ASSERT_STREQ(data
, numbers
);
55 ASSERT_EQ(__llvm_libc::fread(
56 data
, 1, sizeof(format_more
) + sizeof(short_numbers
) - 4, file
),
57 sizeof(format_more
) + sizeof(short_numbers
) - 4);
58 data
[sizeof(format_more
) + sizeof(short_numbers
) - 4] = '\0';
59 ASSERT_STREQ(data
, "1234 and more\n");
61 ASSERT_EQ(__llvm_libc::ferror(file
), 0);
64 __llvm_libc::fprintf(file
, "Writing to a read only file should fail.");
65 EXPECT_LT(written
, 0);
67 ASSERT_EQ(__llvm_libc::fclose(file
), 0);