1 //===-- Unittests for fgetc -----------------------------------------------===//
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/feof.h"
11 #include "src/stdio/feof_unlocked.h"
12 #include "src/stdio/ferror.h"
13 #include "src/stdio/ferror_unlocked.h"
14 #include "src/stdio/fgetc_unlocked.h"
15 #include "src/stdio/flockfile.h"
16 #include "src/stdio/fopen.h"
17 #include "src/stdio/funlockfile.h"
18 #include "src/stdio/fwrite.h"
19 #include "src/stdio/getc_unlocked.h"
20 #include "test/UnitTest/Test.h"
25 class LlvmLibcGetcTest
: public __llvm_libc::testing::Test
{
27 using GetcFunc
= int(FILE *);
28 void test_with_func(GetcFunc
*func
, const char *filename
) {
29 ::FILE *file
= __llvm_libc::fopen(filename
, "w");
30 ASSERT_FALSE(file
== nullptr);
31 constexpr char CONTENT
[] = "123456789";
32 constexpr size_t WRITE_SIZE
= sizeof(CONTENT
) - 1;
33 ASSERT_EQ(WRITE_SIZE
, __llvm_libc::fwrite(CONTENT
, 1, WRITE_SIZE
, file
));
34 // This is a write-only file so reads should fail.
35 ASSERT_EQ(func(file
), EOF
);
36 // This is an error and not a real EOF.
37 ASSERT_EQ(__llvm_libc::feof(file
), 0);
38 ASSERT_NE(__llvm_libc::ferror(file
), 0);
41 ASSERT_EQ(0, __llvm_libc::fclose(file
));
43 file
= __llvm_libc::fopen(filename
, "r");
44 ASSERT_FALSE(file
== nullptr);
46 __llvm_libc::flockfile(file
);
47 for (size_t i
= 0; i
< WRITE_SIZE
; ++i
) {
49 ASSERT_EQ(c
, int('1' + i
));
51 // Reading more should return EOF but not set error.
52 ASSERT_EQ(func(file
), EOF
);
53 ASSERT_NE(__llvm_libc::feof_unlocked(file
), 0);
54 ASSERT_EQ(__llvm_libc::ferror_unlocked(file
), 0);
56 __llvm_libc::funlockfile(file
);
57 ASSERT_EQ(0, __llvm_libc::fclose(file
));
61 TEST_F(LlvmLibcGetcTest
, WriteAndReadCharactersWithFgetcUnlocked
) {
62 test_with_func(&__llvm_libc::fgetc_unlocked
, "testdata/fgetc_unlocked.test");
65 TEST_F(LlvmLibcGetcTest
, WriteAndReadCharactersWithGetcUnlocked
) {
66 test_with_func(&__llvm_libc::getc_unlocked
, "testdata/getc_unlocked.test");