file_util.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <array>
  5. #include <filesystem>
  6. #include <limits>
  7. #include <memory>
  8. #include <sstream>
  9. #include <unordered_map>
  10. #include "common/assert.h"
  11. #include "common/common_funcs.h"
  12. #include "common/common_paths.h"
  13. #include "common/file_util.h"
  14. #include "common/logging/log.h"
  15. #ifdef _WIN32
  16. #include <windows.h>
  17. // windows.h needs to be included before other windows headers
  18. #include <direct.h> // getcwd
  19. #include <io.h>
  20. #include <shellapi.h>
  21. #include <shlobj.h> // for SHGetFolderPath
  22. #include <tchar.h>
  23. #include "common/string_util.h"
  24. #ifdef _MSC_VER
  25. // 64 bit offsets for MSVC
  26. #define fseeko _fseeki64
  27. #define ftello _ftelli64
  28. #define fileno _fileno
  29. #endif
  30. // 64 bit offsets for MSVC and MinGW. MinGW also needs this for using _wstat64
  31. #define stat _stat64
  32. #define fstat _fstat64
  33. #else
  34. #ifdef __APPLE__
  35. #include <sys/param.h>
  36. #endif
  37. #include <cctype>
  38. #include <cerrno>
  39. #include <cstdlib>
  40. #include <cstring>
  41. #include <dirent.h>
  42. #include <pwd.h>
  43. #include <unistd.h>
  44. #endif
  45. #if defined(__APPLE__)
  46. // CFURL contains __attribute__ directives that gcc does not know how to parse, so we need to just
  47. // ignore them if we're not using clang. The macro is only used to prevent linking against
  48. // functions that don't exist on older versions of macOS, and the worst case scenario is a linker
  49. // error, so this is perfectly safe, just inconvenient.
  50. #ifndef __clang__
  51. #define availability(...)
  52. #endif
  53. #include <CoreFoundation/CFBundle.h>
  54. #include <CoreFoundation/CFString.h>
  55. #include <CoreFoundation/CFURL.h>
  56. #ifdef availability
  57. #undef availability
  58. #endif
  59. #endif
  60. #include <algorithm>
  61. #include <sys/stat.h>
  62. namespace Common::FS {
  63. namespace fs = std::filesystem;
  64. bool Exists(const fs::path& path) {
  65. std::error_code ec;
  66. return fs::exists(path, ec);
  67. }
  68. bool IsDirectory(const fs::path& path) {
  69. std::error_code ec;
  70. return fs::is_directory(path, ec);
  71. }
  72. bool Delete(const fs::path& path) {
  73. LOG_TRACE(Common_Filesystem, "file {}", path.string());
  74. // Return true because we care about the file no
  75. // being there, not the actual delete.
  76. if (!Exists(path)) {
  77. LOG_DEBUG(Common_Filesystem, "{} does not exist", path.string());
  78. return true;
  79. }
  80. std::error_code ec;
  81. return fs::remove(path, ec);
  82. }
  83. bool CreateDir(const fs::path& path) {
  84. LOG_TRACE(Common_Filesystem, "directory {}", path.string());
  85. std::error_code ec;
  86. const bool success = fs::create_directory(path, ec);
  87. if (!success) {
  88. LOG_ERROR(Common_Filesystem, "Unable to create directory: {}", ec.message());
  89. return false;
  90. }
  91. return true;
  92. }
  93. bool CreateFullPath(const fs::path& path) {
  94. LOG_TRACE(Common_Filesystem, "path {}", path.string());
  95. std::error_code ec;
  96. const bool success = fs::create_directories(path, ec);
  97. if (!success) {
  98. LOG_ERROR(Common_Filesystem, "Unable to create full path: {}", ec.message());
  99. return false;
  100. }
  101. return true;
  102. }
  103. bool Rename(const fs::path& src, const fs::path& dst) {
  104. LOG_TRACE(Common_Filesystem, "{} --> {}", src.string(), dst.string());
  105. std::error_code ec;
  106. fs::rename(src, dst, ec);
  107. if (ec) {
  108. LOG_ERROR(Common_Filesystem, "Unable to rename file from {} to {}: {}", src.string(),
  109. dst.string(), ec.message());
  110. return false;
  111. }
  112. return true;
  113. }
  114. bool Copy(const fs::path& src, const fs::path& dst) {
  115. LOG_TRACE(Common_Filesystem, "{} --> {}", src.string(), dst.string());
  116. std::error_code ec;
  117. const bool success = fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
  118. if (!success) {
  119. LOG_ERROR(Common_Filesystem, "Unable to copy file {} to {}: {}", src.string(), dst.string(),
  120. ec.message());
  121. return false;
  122. }
  123. return true;
  124. }
  125. u64 GetSize(const fs::path& path) {
  126. std::error_code ec;
  127. const auto size = fs::file_size(path, ec);
  128. if (ec) {
  129. LOG_ERROR(Common_Filesystem, "Unable to retrieve file size ({}): {}", path.string(),
  130. ec.message());
  131. return 0;
  132. }
  133. return size;
  134. }
  135. u64 GetSize(FILE* f) {
  136. // can't use off_t here because it can be 32-bit
  137. u64 pos = ftello(f);
  138. if (fseeko(f, 0, SEEK_END) != 0) {
  139. LOG_ERROR(Common_Filesystem, "GetSize: seek failed {}: {}", fmt::ptr(f), GetLastErrorMsg());
  140. return 0;
  141. }
  142. u64 size = ftello(f);
  143. if ((size != pos) && (fseeko(f, pos, SEEK_SET) != 0)) {
  144. LOG_ERROR(Common_Filesystem, "GetSize: seek failed {}: {}", fmt::ptr(f), GetLastErrorMsg());
  145. return 0;
  146. }
  147. return size;
  148. }
  149. bool CreateEmptyFile(const std::string& filename) {
  150. LOG_TRACE(Common_Filesystem, "{}", filename);
  151. if (!IOFile(filename, "wb").IsOpen()) {
  152. LOG_ERROR(Common_Filesystem, "failed {}: {}", filename, GetLastErrorMsg());
  153. return false;
  154. }
  155. return true;
  156. }
  157. bool ForeachDirectoryEntry(u64* num_entries_out, const std::string& directory,
  158. DirectoryEntryCallable callback) {
  159. LOG_TRACE(Common_Filesystem, "directory {}", directory);
  160. // How many files + directories we found
  161. u64 found_entries = 0;
  162. // Save the status of callback function
  163. bool callback_error = false;
  164. #ifdef _WIN32
  165. // Find the first file in the directory.
  166. WIN32_FIND_DATAW ffd;
  167. HANDLE handle_find = FindFirstFileW(Common::UTF8ToUTF16W(directory + "\\*").c_str(), &ffd);
  168. if (handle_find == INVALID_HANDLE_VALUE) {
  169. FindClose(handle_find);
  170. return false;
  171. }
  172. // windows loop
  173. do {
  174. const std::string virtual_name(Common::UTF16ToUTF8(ffd.cFileName));
  175. #else
  176. DIR* dirp = opendir(directory.c_str());
  177. if (!dirp)
  178. return false;
  179. // non windows loop
  180. while (struct dirent* result = readdir(dirp)) {
  181. const std::string virtual_name(result->d_name);
  182. #endif
  183. if (virtual_name == "." || virtual_name == "..")
  184. continue;
  185. u64 ret_entries = 0;
  186. if (!callback(&ret_entries, directory, virtual_name)) {
  187. callback_error = true;
  188. break;
  189. }
  190. found_entries += ret_entries;
  191. #ifdef _WIN32
  192. } while (FindNextFileW(handle_find, &ffd) != 0);
  193. FindClose(handle_find);
  194. #else
  195. }
  196. closedir(dirp);
  197. #endif
  198. if (callback_error)
  199. return false;
  200. // num_entries_out is allowed to be specified nullptr, in which case we shouldn't try to set it
  201. if (num_entries_out != nullptr)
  202. *num_entries_out = found_entries;
  203. return true;
  204. }
  205. bool DeleteDirRecursively(const fs::path& path) {
  206. std::error_code ec;
  207. fs::remove_all(path, ec);
  208. if (ec) {
  209. LOG_ERROR(Common_Filesystem, "Unable to completely delete directory {}: {}", path.string(),
  210. ec.message());
  211. return false;
  212. }
  213. return true;
  214. }
  215. void CopyDir(const fs::path& src, const fs::path& dst) {
  216. constexpr auto copy_flags = fs::copy_options::skip_existing | fs::copy_options::recursive;
  217. std::error_code ec;
  218. fs::copy(src, dst, copy_flags, ec);
  219. if (ec) {
  220. LOG_ERROR(Common_Filesystem, "Error copying directory {} to {}: {}", src.string(),
  221. dst.string(), ec.message());
  222. return;
  223. }
  224. LOG_TRACE(Common_Filesystem, "Successfully copied directory.");
  225. }
  226. std::optional<fs::path> GetCurrentDir() {
  227. std::error_code ec;
  228. auto path = fs::current_path(ec);
  229. if (ec) {
  230. LOG_ERROR(Common_Filesystem, "Unable to retrieve current working directory: {}",
  231. ec.message());
  232. return std::nullopt;
  233. }
  234. return {std::move(path)};
  235. }
  236. bool SetCurrentDir(const fs::path& path) {
  237. std::error_code ec;
  238. fs::current_path(path, ec);
  239. if (ec) {
  240. LOG_ERROR(Common_Filesystem, "Unable to set {} as working directory: {}", path.string(),
  241. ec.message());
  242. return false;
  243. }
  244. return true;
  245. }
  246. #if defined(__APPLE__)
  247. std::string GetBundleDirectory() {
  248. CFURLRef BundleRef;
  249. char AppBundlePath[MAXPATHLEN];
  250. // Get the main bundle for the app
  251. BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  252. CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
  253. CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
  254. CFRelease(BundleRef);
  255. CFRelease(BundlePath);
  256. return AppBundlePath;
  257. }
  258. #endif
  259. #ifdef _WIN32
  260. const std::string& GetExeDirectory() {
  261. static std::string exe_path;
  262. if (exe_path.empty()) {
  263. wchar_t wchar_exe_path[2048];
  264. GetModuleFileNameW(nullptr, wchar_exe_path, 2048);
  265. exe_path = Common::UTF16ToUTF8(wchar_exe_path);
  266. exe_path = exe_path.substr(0, exe_path.find_last_of('\\'));
  267. }
  268. return exe_path;
  269. }
  270. std::string AppDataRoamingDirectory() {
  271. PWSTR pw_local_path = nullptr;
  272. // Only supported by Windows Vista or later
  273. SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &pw_local_path);
  274. std::string local_path = Common::UTF16ToUTF8(pw_local_path);
  275. CoTaskMemFree(pw_local_path);
  276. return local_path;
  277. }
  278. #else
  279. /**
  280. * @return The user’s home directory on POSIX systems
  281. */
  282. static const std::string& GetHomeDirectory() {
  283. static std::string home_path;
  284. if (home_path.empty()) {
  285. const char* envvar = getenv("HOME");
  286. if (envvar) {
  287. home_path = envvar;
  288. } else {
  289. auto pw = getpwuid(getuid());
  290. ASSERT_MSG(pw,
  291. "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");
  292. home_path = pw->pw_dir;
  293. }
  294. }
  295. return home_path;
  296. }
  297. /**
  298. * Follows the XDG Base Directory Specification to get a directory path
  299. * @param envvar The XDG environment variable to get the value from
  300. * @return The directory path
  301. * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  302. */
  303. static const std::string GetUserDirectory(const std::string& envvar) {
  304. const char* directory = getenv(envvar.c_str());
  305. std::string user_dir;
  306. if (directory) {
  307. user_dir = directory;
  308. } else {
  309. std::string subdirectory;
  310. if (envvar == "XDG_DATA_HOME")
  311. subdirectory = DIR_SEP ".local" DIR_SEP "share";
  312. else if (envvar == "XDG_CONFIG_HOME")
  313. subdirectory = DIR_SEP ".config";
  314. else if (envvar == "XDG_CACHE_HOME")
  315. subdirectory = DIR_SEP ".cache";
  316. else
  317. ASSERT_MSG(false, "Unknown XDG variable {}.", envvar);
  318. user_dir = GetHomeDirectory() + subdirectory;
  319. }
  320. ASSERT_MSG(!user_dir.empty(), "User directory {} mustn’t be empty.", envvar);
  321. ASSERT_MSG(user_dir[0] == '/', "User directory {} must be absolute.", envvar);
  322. return user_dir;
  323. }
  324. #endif
  325. std::string GetSysDirectory() {
  326. std::string sysDir;
  327. #if defined(__APPLE__)
  328. sysDir = GetBundleDirectory();
  329. sysDir += DIR_SEP;
  330. sysDir += SYSDATA_DIR;
  331. #else
  332. sysDir = SYSDATA_DIR;
  333. #endif
  334. sysDir += DIR_SEP;
  335. LOG_DEBUG(Common_Filesystem, "Setting to {}:", sysDir);
  336. return sysDir;
  337. }
  338. const std::string& GetUserPath(UserPath path, const std::string& new_path) {
  339. static std::unordered_map<UserPath, std::string> paths;
  340. auto& user_path = paths[UserPath::UserDir];
  341. // Set up all paths and files on the first run
  342. if (user_path.empty()) {
  343. #ifdef _WIN32
  344. user_path = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
  345. if (!IsDirectory(user_path)) {
  346. user_path = AppDataRoamingDirectory() + DIR_SEP EMU_DATA_DIR DIR_SEP;
  347. } else {
  348. LOG_INFO(Common_Filesystem, "Using the local user directory");
  349. }
  350. paths.emplace(UserPath::ConfigDir, user_path + CONFIG_DIR DIR_SEP);
  351. paths.emplace(UserPath::CacheDir, user_path + CACHE_DIR DIR_SEP);
  352. #else
  353. if (Exists(ROOT_DIR DIR_SEP USERDATA_DIR)) {
  354. user_path = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
  355. paths.emplace(UserPath::ConfigDir, user_path + CONFIG_DIR DIR_SEP);
  356. paths.emplace(UserPath::CacheDir, user_path + CACHE_DIR DIR_SEP);
  357. } else {
  358. std::string data_dir = GetUserDirectory("XDG_DATA_HOME");
  359. std::string config_dir = GetUserDirectory("XDG_CONFIG_HOME");
  360. std::string cache_dir = GetUserDirectory("XDG_CACHE_HOME");
  361. user_path = data_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
  362. paths.emplace(UserPath::ConfigDir, config_dir + DIR_SEP EMU_DATA_DIR DIR_SEP);
  363. paths.emplace(UserPath::CacheDir, cache_dir + DIR_SEP EMU_DATA_DIR DIR_SEP);
  364. }
  365. #endif
  366. paths.emplace(UserPath::SDMCDir, user_path + SDMC_DIR DIR_SEP);
  367. paths.emplace(UserPath::NANDDir, user_path + NAND_DIR DIR_SEP);
  368. paths.emplace(UserPath::LoadDir, user_path + LOAD_DIR DIR_SEP);
  369. paths.emplace(UserPath::DumpDir, user_path + DUMP_DIR DIR_SEP);
  370. paths.emplace(UserPath::ScreenshotsDir, user_path + SCREENSHOTS_DIR DIR_SEP);
  371. paths.emplace(UserPath::ShaderDir, user_path + SHADER_DIR DIR_SEP);
  372. paths.emplace(UserPath::SysDataDir, user_path + SYSDATA_DIR DIR_SEP);
  373. paths.emplace(UserPath::KeysDir, user_path + KEYS_DIR DIR_SEP);
  374. // TODO: Put the logs in a better location for each OS
  375. paths.emplace(UserPath::LogDir, user_path + LOG_DIR DIR_SEP);
  376. }
  377. if (!new_path.empty()) {
  378. if (!IsDirectory(new_path)) {
  379. LOG_ERROR(Common_Filesystem, "Invalid path specified {}", new_path);
  380. return paths[path];
  381. } else {
  382. paths[path] = new_path;
  383. }
  384. switch (path) {
  385. case UserPath::RootDir:
  386. user_path = paths[UserPath::RootDir] + DIR_SEP;
  387. break;
  388. case UserPath::UserDir:
  389. user_path = paths[UserPath::RootDir] + DIR_SEP;
  390. paths[UserPath::ConfigDir] = user_path + CONFIG_DIR DIR_SEP;
  391. paths[UserPath::CacheDir] = user_path + CACHE_DIR DIR_SEP;
  392. paths[UserPath::SDMCDir] = user_path + SDMC_DIR DIR_SEP;
  393. paths[UserPath::NANDDir] = user_path + NAND_DIR DIR_SEP;
  394. break;
  395. default:
  396. break;
  397. }
  398. }
  399. return paths[path];
  400. }
  401. std::string GetHactoolConfigurationPath() {
  402. #ifdef _WIN32
  403. PWSTR pw_local_path = nullptr;
  404. if (SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &pw_local_path) != S_OK)
  405. return "";
  406. std::string local_path = Common::UTF16ToUTF8(pw_local_path);
  407. CoTaskMemFree(pw_local_path);
  408. return local_path + "\\.switch";
  409. #else
  410. return GetHomeDirectory() + "/.switch";
  411. #endif
  412. }
  413. std::string GetNANDRegistrationDir(bool system) {
  414. if (system)
  415. return GetUserPath(UserPath::NANDDir) + "system/Contents/registered/";
  416. return GetUserPath(UserPath::NANDDir) + "user/Contents/registered/";
  417. }
  418. std::size_t WriteStringToFile(bool text_file, const std::string& filename, std::string_view str) {
  419. return IOFile(filename, text_file ? "w" : "wb").WriteString(str);
  420. }
  421. std::size_t ReadFileToString(bool text_file, const std::string& filename, std::string& str) {
  422. IOFile file(filename, text_file ? "r" : "rb");
  423. if (!file.IsOpen())
  424. return 0;
  425. str.resize(static_cast<u32>(file.GetSize()));
  426. return file.ReadArray(&str[0], str.size());
  427. }
  428. void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
  429. std::array<char, 4>& extension) {
  430. static constexpr std::string_view forbidden_characters = ".\"/\\[]:;=, ";
  431. // On a FAT32 partition, 8.3 names are stored as a 11 bytes array, filled with spaces.
  432. short_name = {{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'}};
  433. extension = {{' ', ' ', ' ', '\0'}};
  434. auto point = filename.rfind('.');
  435. if (point == filename.size() - 1) {
  436. point = filename.rfind('.', point);
  437. }
  438. // Get short name.
  439. int j = 0;
  440. for (char letter : filename.substr(0, point)) {
  441. if (forbidden_characters.find(letter, 0) != std::string::npos) {
  442. continue;
  443. }
  444. if (j == 8) {
  445. // TODO(Link Mauve): also do that for filenames containing a space.
  446. // TODO(Link Mauve): handle multiple files having the same short name.
  447. short_name[6] = '~';
  448. short_name[7] = '1';
  449. break;
  450. }
  451. short_name[j++] = static_cast<char>(std::toupper(letter));
  452. }
  453. // Get extension.
  454. if (point != std::string::npos) {
  455. j = 0;
  456. for (char letter : filename.substr(point + 1, 3)) {
  457. extension[j++] = static_cast<char>(std::toupper(letter));
  458. }
  459. }
  460. }
  461. std::vector<std::string> SplitPathComponents(std::string_view filename) {
  462. std::string copy(filename);
  463. std::replace(copy.begin(), copy.end(), '\\', '/');
  464. std::vector<std::string> out;
  465. std::stringstream stream(copy);
  466. std::string item;
  467. while (std::getline(stream, item, '/')) {
  468. out.push_back(std::move(item));
  469. }
  470. return out;
  471. }
  472. std::string_view GetParentPath(std::string_view path) {
  473. const auto name_bck_index = path.rfind('\\');
  474. const auto name_fwd_index = path.rfind('/');
  475. std::size_t name_index;
  476. if (name_bck_index == std::string_view::npos || name_fwd_index == std::string_view::npos) {
  477. name_index = std::min(name_bck_index, name_fwd_index);
  478. } else {
  479. name_index = std::max(name_bck_index, name_fwd_index);
  480. }
  481. return path.substr(0, name_index);
  482. }
  483. std::string_view GetPathWithoutTop(std::string_view path) {
  484. if (path.empty()) {
  485. return path;
  486. }
  487. while (path[0] == '\\' || path[0] == '/') {
  488. path.remove_prefix(1);
  489. if (path.empty()) {
  490. return path;
  491. }
  492. }
  493. const auto name_bck_index = path.find('\\');
  494. const auto name_fwd_index = path.find('/');
  495. return path.substr(std::min(name_bck_index, name_fwd_index) + 1);
  496. }
  497. std::string_view GetFilename(std::string_view path) {
  498. const auto name_index = path.find_last_of("\\/");
  499. if (name_index == std::string_view::npos) {
  500. return {};
  501. }
  502. return path.substr(name_index + 1);
  503. }
  504. std::string_view GetExtensionFromFilename(std::string_view name) {
  505. const std::size_t index = name.rfind('.');
  506. if (index == std::string_view::npos) {
  507. return {};
  508. }
  509. return name.substr(index + 1);
  510. }
  511. std::string_view RemoveTrailingSlash(std::string_view path) {
  512. if (path.empty()) {
  513. return path;
  514. }
  515. if (path.back() == '\\' || path.back() == '/') {
  516. path.remove_suffix(1);
  517. return path;
  518. }
  519. return path;
  520. }
  521. std::string SanitizePath(std::string_view path_, DirectorySeparator directory_separator) {
  522. std::string path(path_);
  523. char type1 = directory_separator == DirectorySeparator::BackwardSlash ? '/' : '\\';
  524. char type2 = directory_separator == DirectorySeparator::BackwardSlash ? '\\' : '/';
  525. if (directory_separator == DirectorySeparator::PlatformDefault) {
  526. #ifdef _WIN32
  527. type1 = '/';
  528. type2 = '\\';
  529. #endif
  530. }
  531. std::replace(path.begin(), path.end(), type1, type2);
  532. auto start = path.begin();
  533. #ifdef _WIN32
  534. // allow network paths which start with a double backslash (e.g. \\server\share)
  535. if (start != path.end())
  536. ++start;
  537. #endif
  538. path.erase(std::unique(start, path.end(),
  539. [type2](char c1, char c2) { return c1 == type2 && c2 == type2; }),
  540. path.end());
  541. return std::string(RemoveTrailingSlash(path));
  542. }
  543. IOFile::IOFile() = default;
  544. IOFile::IOFile(const std::string& filename, const char openmode[], int flags) {
  545. void(Open(filename, openmode, flags));
  546. }
  547. IOFile::~IOFile() {
  548. Close();
  549. }
  550. IOFile::IOFile(IOFile&& other) noexcept {
  551. Swap(other);
  552. }
  553. IOFile& IOFile::operator=(IOFile&& other) noexcept {
  554. Swap(other);
  555. return *this;
  556. }
  557. void IOFile::Swap(IOFile& other) noexcept {
  558. std::swap(m_file, other.m_file);
  559. }
  560. bool IOFile::Open(const std::string& filename, const char openmode[], int flags) {
  561. Close();
  562. bool m_good;
  563. #ifdef _WIN32
  564. if (flags != 0) {
  565. m_file = _wfsopen(Common::UTF8ToUTF16W(filename).c_str(),
  566. Common::UTF8ToUTF16W(openmode).c_str(), flags);
  567. m_good = m_file != nullptr;
  568. } else {
  569. m_good = _wfopen_s(&m_file, Common::UTF8ToUTF16W(filename).c_str(),
  570. Common::UTF8ToUTF16W(openmode).c_str()) == 0;
  571. }
  572. #else
  573. m_file = std::fopen(filename.c_str(), openmode);
  574. m_good = m_file != nullptr;
  575. #endif
  576. return m_good;
  577. }
  578. bool IOFile::Close() {
  579. if (!IsOpen() || 0 != std::fclose(m_file)) {
  580. return false;
  581. }
  582. m_file = nullptr;
  583. return true;
  584. }
  585. u64 IOFile::GetSize() const {
  586. if (IsOpen()) {
  587. return FS::GetSize(m_file);
  588. }
  589. return 0;
  590. }
  591. bool IOFile::Seek(s64 off, int origin) const {
  592. return IsOpen() && 0 == fseeko(m_file, off, origin);
  593. }
  594. u64 IOFile::Tell() const {
  595. if (IsOpen()) {
  596. return ftello(m_file);
  597. }
  598. return std::numeric_limits<u64>::max();
  599. }
  600. bool IOFile::Flush() {
  601. return IsOpen() && 0 == std::fflush(m_file);
  602. }
  603. std::size_t IOFile::ReadImpl(void* data, std::size_t length, std::size_t data_size) const {
  604. if (!IsOpen()) {
  605. return std::numeric_limits<std::size_t>::max();
  606. }
  607. if (length == 0) {
  608. return 0;
  609. }
  610. DEBUG_ASSERT(data != nullptr);
  611. return std::fread(data, data_size, length, m_file);
  612. }
  613. std::size_t IOFile::WriteImpl(const void* data, std::size_t length, std::size_t data_size) {
  614. if (!IsOpen()) {
  615. return std::numeric_limits<std::size_t>::max();
  616. }
  617. if (length == 0) {
  618. return 0;
  619. }
  620. DEBUG_ASSERT(data != nullptr);
  621. return std::fwrite(data, data_size, length, m_file);
  622. }
  623. bool IOFile::Resize(u64 size) {
  624. return IsOpen() && 0 ==
  625. #ifdef _WIN32
  626. // ector: _chsize sucks, not 64-bit safe
  627. // F|RES: changed to _chsize_s. i think it is 64-bit safe
  628. _chsize_s(_fileno(m_file), size)
  629. #else
  630. // TODO: handle 64bit and growing
  631. ftruncate(fileno(m_file), size)
  632. #endif
  633. ;
  634. }
  635. } // namespace Common::FS