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