From eb2dd8ebd7a0831b07f8d187eb2686e5d9179ace Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 30 Apr 2024 18:36:50 +0200 Subject: [PATCH] Codechange: make using a RAII managed FILE* less clunky --- src/dedicated.cpp | 2 +- src/fileio.cpp | 4 ++-- src/fileio_func.h | 5 ++++- src/highscore.cpp | 4 ++-- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/dedicated.cpp b/src/dedicated.cpp index df457f2559..1b8759db81 100644 --- a/src/dedicated.cpp +++ b/src/dedicated.cpp @@ -12,7 +12,7 @@ #include "debug.h" std::string _log_file; ///< File to reroute output of a forked OpenTTD to -std::unique_ptr _log_fd; ///< File to reroute output of a forked OpenTTD to +AutoCloseFile _log_fd; ///< File to reroute output of a forked OpenTTD to #if defined(UNIX) diff --git a/src/fileio.cpp b/src/fileio.cpp index c99ec88bc1..1ef7ea3e3a 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -638,14 +638,14 @@ bool ExtractTar(const std::string &tar_filename, Subdirectory subdir) /* First open the file in the .tar. */ size_t to_copy = 0; - std::unique_ptr in(FioFOpenFileTar(it2.second, &to_copy)); + AutoCloseFile in(FioFOpenFileTar(it2.second, &to_copy)); if (!in) { Debug(misc, 6, "Extracting {} failed; could not open {}", filename, tar_filename); return false; } /* Now open the 'output' file. */ - std::unique_ptr out(fopen(filename.c_str(), "wb")); + AutoCloseFile out(fopen(filename.c_str(), "wb")); if (!out) { Debug(misc, 6, "Extracting {} failed; could not open {}", filename, filename); return false; diff --git a/src/fileio_func.h b/src/fileio_func.h index eaa6f76164..0aa24403c5 100644 --- a/src/fileio_func.h +++ b/src/fileio_func.h @@ -97,8 +97,11 @@ public: struct FileDeleter { void operator()(FILE *f) { - if (f) fclose(f); + if (f != nullptr) fclose(f); } }; +/** Helper type for RAII management of a FILE that gets closed when it goes out of scope. */ +using AutoCloseFile = std::unique_ptr; + #endif /* FILEIO_FUNC_H */ diff --git a/src/highscore.cpp b/src/highscore.cpp index f6fd57978b..ee04b07f05 100644 --- a/src/highscore.cpp +++ b/src/highscore.cpp @@ -122,7 +122,7 @@ int8_t SaveHighScoreValueNetwork() /** Save HighScore table to file */ void SaveToHighScore() { - std::unique_ptr fp(fopen(_highscore_file.c_str(), "wb")); + AutoCloseFile fp(fopen(_highscore_file.c_str(), "wb")); if (fp == nullptr) return; /* Does not iterate through the complete array!. */ @@ -146,7 +146,7 @@ void LoadFromHighScore() { std::fill(_highscore_table.begin(), _highscore_table.end(), HighScores{}); - std::unique_ptr fp(fopen(_highscore_file.c_str(), "rb")); + AutoCloseFile fp(fopen(_highscore_file.c_str(), "rb")); if (fp == nullptr) return; /* Does not iterate through the complete array!. */