Skip to content

Commit ea98470

Browse files
authored
Fix file handle closing in case of an error (#182)
Move out the common code for libstdc++ and libc++ implementations
1 parent 6847dd7 commit ea98470

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/file.cpp

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -148,29 +148,30 @@ file::file(std::ios::openmode mode)
148148
#if defined(_MSC_VER)
149149
,
150150
underlying(nullptr, &std::fclose)
151+
#elif defined(_LIBCPP_VERSION)
152+
,
153+
handle(create_file())
151154
#endif
152155
{
153156
mode |= std::ios::in | std::ios::out;
154157

155158
#if defined(__GLIBCXX__)
156159
int handle = create_file();
157160
sb = __gnu_cxx::stdio_filebuf<char>(handle, mode);
158-
if (!sb.is_open()) {
159-
close(handle);
160-
throw fs::filesystem_error("", std::make_error_code(std::io_errc::stream));
161-
}
162161
#elif defined(_LIBCPP_VERSION)
163-
this->handle = create_file();
164162
sb.__open(handle, mode);
165-
if (!sb.is_open()) {
166-
close(handle);
167-
throw fs::filesystem_error("", std::make_error_code(std::io_errc::stream));
168-
}
169163
#else // MSVC
170-
std::FILE* handle = create_file(mode);
171-
underlying.reset(handle);
164+
underlying.reset(create_file(mode));
172165
sb = std::filebuf(underlying.get());
173166
#endif
167+
168+
if (!sb.is_open()) {
169+
#ifndef _WIN32
170+
close(handle);
171+
#endif
172+
std::error_code ec = std::make_error_code(std::io_errc::stream);
173+
throw fs::filesystem_error("Cannot open a temporary file", ec);
174+
}
174175
}
175176

176177
file file::copy(const fs::path& path, std::ios::openmode mode) {

0 commit comments

Comments
 (0)