1//===-- Unittests for f operations like fopen, flcose etc --------------===//
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_unlocked.h"
10#include "src/stdio/fclose.h"
11#include "src/stdio/feof_unlocked.h"
12#include "src/stdio/ferror_unlocked.h"
13#include "src/stdio/flockfile.h"
14#include "src/stdio/fopen.h"
15#include "src/stdio/fread_unlocked.h"
16#include "src/stdio/funlockfile.h"
17#include "src/stdio/fwrite_unlocked.h"
18#include "test/UnitTest/Test.h"
19
20#include "src/errno/libc_errno.h"
21#include <stdio.h>
22
23TEST(LlvmLibcFILETest, UnlockedReadAndWrite) {
24 constexpr char fNAME[] = "testdata/unlocked_read_and_write.test";
25 ::FILE *f = LIBC_NAMESPACE::fopen(name: fNAME, mode: "w");
26 ASSERT_FALSE(f == nullptr);
27 constexpr char CONTENT[] = "1234567890987654321";
28 LIBC_NAMESPACE::flockfile(stream: f);
29 ASSERT_EQ(sizeof(CONTENT) - 1, LIBC_NAMESPACE::fwrite_unlocked(
30 CONTENT, 1, sizeof(CONTENT) - 1, f));
31 // Should be an error to read.
32 constexpr size_t READ_SIZE = 5;
33 char data[READ_SIZE * 2 + 1];
34 data[READ_SIZE * 2] = '\0';
35
36 ASSERT_EQ(size_t(0),
37 LIBC_NAMESPACE::fread_unlocked(data, 1, sizeof(READ_SIZE), f));
38 ASSERT_NE(LIBC_NAMESPACE::ferror_unlocked(f), 0);
39 ASSERT_ERRNO_FAILURE();
40 LIBC_NAMESPACE::libc_errno = 0;
41
42 LIBC_NAMESPACE::clearerr_unlocked(stream: f);
43 ASSERT_EQ(LIBC_NAMESPACE::ferror_unlocked(f), 0);
44
45 LIBC_NAMESPACE::funlockfile(stream: f);
46 ASSERT_EQ(0, LIBC_NAMESPACE::fclose(f));
47
48 f = LIBC_NAMESPACE::fopen(name: fNAME, mode: "r");
49 ASSERT_FALSE(f == nullptr);
50
51 LIBC_NAMESPACE::flockfile(stream: f);
52 ASSERT_EQ(LIBC_NAMESPACE::fread_unlocked(data, 1, READ_SIZE, f), READ_SIZE);
53 ASSERT_EQ(LIBC_NAMESPACE::fread_unlocked(data + READ_SIZE, 1, READ_SIZE, f),
54 READ_SIZE);
55
56 // Should be an error to write.
57 ASSERT_EQ(size_t(0),
58 LIBC_NAMESPACE::fwrite_unlocked(CONTENT, 1, sizeof(CONTENT), f));
59 ASSERT_NE(LIBC_NAMESPACE::ferror_unlocked(f), 0);
60 ASSERT_ERRNO_FAILURE();
61 LIBC_NAMESPACE::libc_errno = 0;
62
63 LIBC_NAMESPACE::clearerr_unlocked(stream: f);
64 ASSERT_EQ(LIBC_NAMESPACE::ferror_unlocked(f), 0);
65
66 // Reading more should trigger eof.
67 char large_data[sizeof(CONTENT)];
68 ASSERT_NE(sizeof(CONTENT),
69 LIBC_NAMESPACE::fread_unlocked(large_data, 1, sizeof(CONTENT), f));
70 ASSERT_NE(LIBC_NAMESPACE::feof_unlocked(f), 0);
71
72 LIBC_NAMESPACE::funlockfile(stream: f);
73 ASSERT_STREQ(data, "1234567890");
74
75 ASSERT_EQ(LIBC_NAMESPACE::fclose(f), 0);
76}
77

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