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
20namespace printf_test {
21#ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
22using LIBC_NAMESPACE::fclose;
23using LIBC_NAMESPACE::ferror;
24using LIBC_NAMESPACE::fopen;
25using LIBC_NAMESPACE::fread;
26#else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
27using ::fclose;
28using ::ferror;
29using ::fopen;
30using ::fread;
31#endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
32} // namespace printf_test
33
34TEST(LlvmLibcFPrintfTest, WriteToFile) {
35 const char *FILENAME = "fprintf_output.test";
36 auto FILE_PATH = libc_make_test_file_path(FILENAME);
37
38 ::FILE *file = printf_test::fopen(FILE_PATH, "w");
39 ASSERT_FALSE(file == nullptr);
40
41 int written;
42
43 constexpr char simple[] = "A simple string with no conversions.\n";
44 written = LIBC_NAMESPACE::fprintf(file, simple);
45 EXPECT_EQ(written, 37);
46
47 constexpr char numbers[] = "1234567890\n";
48 written = LIBC_NAMESPACE::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 = LIBC_NAMESPACE::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(FILE_PATH, "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 LIBC_NAMESPACE::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

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

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