1 //===-- Unittests for file 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/fclose.h" 10 #include "src/stdio/fflush.h" 11 #include "src/stdio/fopen.h" 12 #include "src/stdio/fread.h" 13 #include "src/stdio/fseek.h" 14 #include "src/stdio/fwrite.h" 15 #include "utils/UnitTest/Test.h" 16 17 #include <stdio.h> 18 19 TEST(LlvmLibcStdio, SimpleOperations) { 20 constexpr char FILENAME[] = "testdata/simple_operations.test"; 21 ::FILE *file = __llvm_libc::fopen(FILENAME, "w"); 22 ASSERT_FALSE(file == nullptr); 23 constexpr char CONTENT[] = "1234567890987654321"; 24 ASSERT_EQ(sizeof(CONTENT) - 1, 25 __llvm_libc::fwrite(CONTENT, 1, sizeof(CONTENT) - 1, file)); 26 ASSERT_EQ(0, __llvm_libc::fclose(file)); 27 28 file = __llvm_libc::fopen(FILENAME, "r"); 29 ASSERT_FALSE(file == nullptr); 30 31 constexpr size_t READ_SIZE = 5; 32 char data[READ_SIZE]; 33 data[READ_SIZE - 1] = '\0'; 34 ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1); 35 ASSERT_STREQ(data, "1234"); 36 ASSERT_EQ(__llvm_libc::fseek(file, 5, SEEK_CUR), 0); 37 ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1); 38 ASSERT_STREQ(data, "0987"); 39 ASSERT_EQ(__llvm_libc::fseek(file, -5, SEEK_CUR), 0); 40 ASSERT_EQ(__llvm_libc::fread(data, 1, READ_SIZE - 1, file), READ_SIZE - 1); 41 ASSERT_STREQ(data, "9098"); 42 43 ASSERT_EQ(__llvm_libc::fclose(file), 0); 44 } 45 46 TEST(LlvmLibcFILE, FFlushTest) { 47 constexpr char FILENAME[] = "testdata/fflush.test"; 48 ::FILE *file = __llvm_libc::fopen(FILENAME, "w+"); 49 ASSERT_FALSE(file == nullptr); 50 constexpr char CONTENT[] = "1234567890987654321"; 51 ASSERT_EQ(sizeof(CONTENT), 52 __llvm_libc::fwrite(CONTENT, 1, sizeof(CONTENT), file)); 53 54 // Flushing at this point should write the data to disk. So, we should be 55 // able to read it back. 56 ASSERT_EQ(0, __llvm_libc::fflush(file)); 57 58 char data[sizeof(CONTENT)]; 59 ASSERT_EQ(__llvm_libc::fseek(file, 0, SEEK_SET), 0); 60 ASSERT_EQ(__llvm_libc::fread(data, 1, sizeof(CONTENT), file), 61 sizeof(CONTENT)); 62 ASSERT_STREQ(data, CONTENT); 63 64 ASSERT_EQ(__llvm_libc::fclose(file), 0); 65 } 66