1//===-- Unittests for fgetc -----------------------------------------------===//
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/clearerr.h"
10#include "src/stdio/fclose.h"
11#include "src/stdio/feof.h"
12#include "src/stdio/ferror.h"
13#include "src/stdio/fgetc.h"
14#include "src/stdio/fopen.h"
15#include "src/stdio/fwrite.h"
16#include "src/stdio/getc.h"
17#include "test/UnitTest/Test.h"
18
19#include "src/errno/libc_errno.h"
20#include <stdio.h>
21
22class LlvmLibcGetcTest : public LIBC_NAMESPACE::testing::Test {
23public:
24 using GetcFunc = int(FILE *);
25 void test_with_func(GetcFunc *func, const char *filename) {
26 ::FILE *file = LIBC_NAMESPACE::fopen(name: filename, mode: "w");
27 ASSERT_FALSE(file == nullptr);
28 constexpr char CONTENT[] = "123456789";
29 constexpr size_t WRITE_SIZE = sizeof(CONTENT) - 1;
30 ASSERT_EQ(WRITE_SIZE, LIBC_NAMESPACE::fwrite(CONTENT, 1, WRITE_SIZE, file));
31 // This is a write-only file so reads should fail.
32 ASSERT_EQ(func(file), EOF);
33 // This is an error and not a real EOF.
34 ASSERT_EQ(LIBC_NAMESPACE::feof(file), 0);
35 ASSERT_NE(LIBC_NAMESPACE::ferror(file), 0);
36 LIBC_NAMESPACE::libc_errno = 0;
37
38 ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
39
40 file = LIBC_NAMESPACE::fopen(name: filename, mode: "r");
41 ASSERT_FALSE(file == nullptr);
42
43 for (size_t i = 0; i < WRITE_SIZE; ++i) {
44 int c = func(file);
45 ASSERT_EQ(c, int('1' + i));
46 }
47 // Reading more should return EOF but not set error.
48 ASSERT_EQ(func(file), EOF);
49 ASSERT_NE(LIBC_NAMESPACE::feof(file), 0);
50 ASSERT_EQ(LIBC_NAMESPACE::ferror(file), 0);
51
52 ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
53 }
54};
55
56TEST_F(LlvmLibcGetcTest, WriteAndReadCharactersWithFgetc) {
57 test_with_func(func: &LIBC_NAMESPACE::fgetc, filename: "testdata/fgetc.test");
58}
59
60TEST_F(LlvmLibcGetcTest, WriteAndReadCharactersWithGetc) {
61 test_with_func(func: &LIBC_NAMESPACE::getc, filename: "testdata/getc.test");
62}
63

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