diff --git a/libcxx/src/filesystem/operations.cpp b/libcxx/src/filesystem/operations.cpp --- a/libcxx/src/filesystem/operations.cpp +++ b/libcxx/src/filesystem/operations.cpp @@ -1416,12 +1416,14 @@ 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;