Codechange: Use directory_iterator to find language files. (#12495)

This avoids using custom ttd_opendir, along with C-style string comparisons against file names.
This commit is contained in:
Peter Nelson 2024-04-14 23:57:26 +01:00 committed by GitHub
parent 4eaeccdaeb
commit 839f486074
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 18 additions and 22 deletions

View File

@ -2050,9 +2050,9 @@ const LanguageMetadata *GetLanguage(uint8_t newgrflangid)
* @param hdr the place to write the header information to * @param hdr the place to write the header information to
* @return true if and only if the language file is of a compatible version * @return true if and only if the language file is of a compatible version
*/ */
static bool GetLanguageFileHeader(const char *file, LanguagePackHeader *hdr) static bool GetLanguageFileHeader(const std::string &file, LanguagePackHeader *hdr)
{ {
FILE *f = fopen(file, "rb"); FILE *f = fopen(file.c_str(), "rb");
if (f == nullptr) return false; if (f == nullptr) return false;
size_t read = fread(hdr, sizeof(*hdr), 1, f); size_t read = fread(hdr, sizeof(*hdr), 1, f);
@ -2074,29 +2074,25 @@ static bool GetLanguageFileHeader(const char *file, LanguagePackHeader *hdr)
*/ */
static void FillLanguageList(const std::string &path) static void FillLanguageList(const std::string &path)
{ {
DIR *dir = ttd_opendir(path.c_str()); std::error_code error_code;
if (dir != nullptr) { for (const auto &dir_entry : std::filesystem::directory_iterator(OTTD2FS(path), error_code)) {
struct dirent *dirent; if (!dir_entry.is_regular_file()) continue;
while ((dirent = readdir(dir)) != nullptr) { if (dir_entry.path().extension() != ".lng") continue;
std::string d_name = FS2OTTD(dirent->d_name);
const char *extension = strrchr(d_name.c_str(), '.');
/* Not a language file */ LanguageMetadata lmd;
if (extension == nullptr || strcmp(extension, ".lng") != 0) continue; lmd.file = FS2OTTD(dir_entry.path());
LanguageMetadata lmd; /* Check whether the file is of the correct version */
lmd.file = path + d_name; if (!GetLanguageFileHeader(lmd.file.string(), &lmd)) {
Debug(misc, 3, "{} is not a valid language file", lmd.file);
/* Check whether the file is of the correct version */ } else if (GetLanguage(lmd.newgrflangid) != nullptr) {
if (!GetLanguageFileHeader(lmd.file.string().c_str(), &lmd)) { Debug(misc, 3, "{}'s language ID is already known", lmd.file);
Debug(misc, 3, "{} is not a valid language file", lmd.file); } else {
} else if (GetLanguage(lmd.newgrflangid) != nullptr) { _languages.push_back(lmd);
Debug(misc, 3, "{}'s language ID is already known", lmd.file);
} else {
_languages.push_back(lmd);
}
} }
closedir(dir); }
if (error_code) {
Debug(misc, 9, "Unable to open directory {}: {}", path, error_code.message());
} }
} }