diff --git a/libcxx/src/filesystem/operations.cpp b/libcxx/src/filesystem/operations.cpp index 7aeeffaae8f38..39fb5739739be 100644 --- a/libcxx/src/filesystem/operations.cpp +++ b/libcxx/src/filesystem/operations.cpp @@ -1414,12 +1414,14 @@ uintmax_t remove_all_impl(int parent_directory, const path& p, error_code& ec) { if (fd != -1) { // If that worked, iterate over the contents of the directory and // remove everything in it, recursively. - scope_exit close_fd([=] { ::close(fd); }); DIR* stream = ::fdopendir(fd); if (stream == nullptr) { + ::close(fd); ec = detail::capture_errno(); return 0; } + // Note: `::closedir` will also close the associated file descriptor, so + // there should be no call to `close(fd)`. scope_exit close_stream([=] { ::closedir(stream); }); uintmax_t count = 0;