60 lines · cpp
1//===----------------------------------------------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9// <fstream>10 11// basic_filebuf<charT,traits>* close();12 13#include <fstream>14#include <cassert>15#if defined(__unix__)16#include <fcntl.h>17#include <unistd.h>18#endif19#include "test_macros.h"20#include "platform_support.h"21 22int main(int, char**)23{24 std::string temp = get_temp_file_name();25 {26 std::filebuf f;27 assert(!f.is_open());28 assert(f.open(temp.c_str(), std::ios_base::out) != 0);29 assert(f.is_open());30 assert(f.close() != nullptr);31 assert(!f.is_open());32 assert(f.close() == nullptr);33 assert(!f.is_open());34 }35 // Starting with Android API 30+, Bionic's fdsan aborts a process that calls36 // close() on a file descriptor tagged as belonging to something else (such37 // as a FILE*).38#if defined(__unix__) && !defined(__BIONIC__)39 {40 std::filebuf f;41 assert(!f.is_open());42 // Use open directly to get the file descriptor.43 int fd = open(temp.c_str(), O_RDWR);44 assert(fd >= 0);45 // Use the internal method to create filebuf from the file descriptor.46 assert(f.__open(fd, std::ios_base::out) != 0);47 assert(f.is_open());48 // Close the file descriptor directly to force filebuf::close to fail.49 assert(close(fd) == 0);50 // Ensure that filebuf::close handles the failure.51 assert(f.close() == nullptr);52 assert(!f.is_open());53 assert(f.close() == nullptr);54 }55#endif56 std::remove(temp.c_str());57 58 return 0;59}60