1
0
Fork 0

Codechange: make using a RAII managed FILE* less clunky

pull/12597/head
Rubidium 2024-04-30 18:36:50 +02:00
parent 4df44fea38
commit eb2dd8ebd7
4 changed files with 9 additions and 6 deletions

View File

@ -12,7 +12,7 @@
#include "debug.h"
std::string _log_file; ///< File to reroute output of a forked OpenTTD to
std::unique_ptr<FILE, FileDeleter> _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)

View File

@ -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<FILE, FileDeleter> 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<FILE, FileDeleter> 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;

View File

@ -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<FILE, FileDeleter>;
#endif /* FILEIO_FUNC_H */

View File

@ -122,7 +122,7 @@ int8_t SaveHighScoreValueNetwork()
/** Save HighScore table to file */
void SaveToHighScore()
{
std::unique_ptr<FILE, FileDeleter> 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<FILE, FileDeleter> 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!. */