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 #include "src/stdio/fclose.h" 10 #include "src/stdio/ferror.h" 11 #include "src/stdio/fopen.h" 12 #include "src/stdio/fread.h" 13 14 #include "src/stdio/fprintf.h" 15 16 #include "utils/UnitTest/Test.h" 17 18 #include <errno.h> 19 #include <stdio.h> 20 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); 25 26 int written; 27 28 constexpr char simple[] = "A simple string with no conversions.\n"; 29 written = __llvm_libc::fprintf(file, simple); 30 EXPECT_EQ(written, 37); 31 32 constexpr char numbers[] = "1234567890\n"; 33 written = __llvm_libc::fprintf(file, "%s", numbers); 34 EXPECT_EQ(written, 11); 35 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); 40 41 ASSERT_EQ(0, __llvm_libc::fclose(file)); 42 43 file = __llvm_libc::fopen(FILENAME, "r"); 44 ASSERT_FALSE(file == nullptr); 45 46 char data[50]; 47 ASSERT_EQ(__llvm_libc::fread(data, 1, sizeof(simple) - 1, file), 48 sizeof(simple) - 1); 49 data[sizeof(simple) - 1] = '\0'; 50 ASSERT_STREQ(data, simple); 51 ASSERT_EQ(__llvm_libc::fread(data, 1, sizeof(numbers) - 1, file), 52 sizeof(numbers) - 1); 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"); 60 61 ASSERT_EQ(__llvm_libc::ferror(file), 0); 62 63 written = 64 __llvm_libc::fprintf(file, "Writing to a read only file should fail."); 65 EXPECT_LT(written, 0); 66 67 ASSERT_EQ(__llvm_libc::fclose(file), 0); 68 } 69