From 55d00feb3c9b253153391e8ec35d893f56e89c7d Mon Sep 17 00:00:00 2001 From: lifegpc Date: Wed, 19 Mar 2025 09:01:14 +0800 Subject: [PATCH] Add fopen to utils --- fileop.cpp | 21 +++++++++++++++++++++ fileop.h | 1 + 2 files changed, 22 insertions(+) diff --git a/fileop.cpp b/fileop.cpp index e503901..ab2f910 100644 --- a/fileop.cpp +++ b/fileop.cpp @@ -45,6 +45,10 @@ bool exists_internal(wchar_t* fn) { return !_waccess(fn, 0); } +FILE* fopen_internal(wchar_t* fn, const wchar_t* mode) { + return _wfopen(fn, mode); +} + bool remove_internal(wchar_t* fn, bool print_error) { int ret = _wremove(fn); if (ret && print_error && errno != ENOENT) { @@ -667,3 +671,20 @@ std::string fileop::relpath(std::string path, std::string start) { return result; } + +FILE* fileop::fopen(std::string path, std::string mode) { +#if _WIN32 + std::wstring wMode; + if (wchar_util::str_to_wstr(wMode, mode, CP_UTF8)) { + UINT cp[] = { CP_UTF8, CP_OEMCP, CP_ACP }; + int i; + for (i = 0; i < 3; i++) { + auto f = fileop_internal(path.c_str(), cp[i], &fopen_internal, nullptr, wMode.c_str()); + if (f) return f; + } + } + return ::fopen(path.c_str(), mode.c_str()); +#else + return ::fopen(path.c_str(), mode.c_str()); +#endif +} diff --git a/fileop.h b/fileop.h index 4996e68..81686aa 100644 --- a/fileop.h +++ b/fileop.h @@ -182,5 +182,6 @@ namespace fileop { * @return Result */ std::string relpath(std::string path, std::string start = ""); + FILE* fopen(std::string path, std::string mode); } #endif