Skip to content

Commit

Permalink
fileutil.hpp: change deleter of fileptr_t
Browse files Browse the repository at this point in the history
  • Loading branch information
wojdyr committed May 28, 2024
1 parent 61fc1c8 commit e69466d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
14 changes: 11 additions & 3 deletions include/gemmi/fileutil.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,16 @@ inline std::string path_basename(const std::string& path,
return basename;
}

struct fileptr_close {
bool needs_fclose;
void operator()(FILE* f) const noexcept {
if (needs_fclose)
std::fclose(f);
}
};

// file operations
typedef std::unique_ptr<std::FILE, decltype(&std::fclose)> fileptr_t;
typedef std::unique_ptr<std::FILE, fileptr_close> fileptr_t;

inline fileptr_t file_open(const char* path, const char* mode) {
std::FILE* file;
Expand All @@ -47,14 +55,14 @@ inline fileptr_t file_open(const char* path, const char* mode) {
#endif
sys_fail(std::string("Failed to open ") + path +
(*mode == 'w' ? " for writing" : ""));
return fileptr_t(file, &std::fclose);
return fileptr_t(file, fileptr_close{true});
}

// helper function for treating "-" as stdin or stdout
inline fileptr_t file_open_or(const char* path, const char* mode,
std::FILE* dash_stream) {
if (path[0] == '-' && path[1] == '\0')
return fileptr_t(dash_stream, [](std::FILE*) { return 0; });
return fileptr_t(dash_stream, fileptr_close{false});
return file_open(path, mode);
}

Expand Down
2 changes: 1 addition & 1 deletion prog/sfcalc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ void process_with_fft(const gemmi::Structure& st,
}
gemmi::StructureFactorCalculator<Table> calc(st.cell);
calc.addends = dencalc.addends;
gemmi::fileptr_t cache(nullptr, nullptr);
gemmi::fileptr_t cache(nullptr, gemmi::fileptr_close{false});
gemmi::AsuData<std::complex<double>> compared_data;
if (file.path) {
if (file.mode == RefFile::Mode::Test) {
Expand Down

0 comments on commit e69466d

Please sign in to comment.