file_util.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include "common/common.h"
  5. #include "common/file_util.h"
  6. #ifdef _WIN32
  7. #include <windows.h>
  8. #include <shlobj.h> // for SHGetFolderPath
  9. #include <shellapi.h>
  10. #include <commdlg.h> // for GetSaveFileName
  11. #include <io.h>
  12. #include <direct.h> // getcwd
  13. #else
  14. #include <sys/param.h>
  15. #include <dirent.h>
  16. #endif
  17. #if defined(__APPLE__)
  18. #include <CoreFoundation/CFString.h>
  19. #include <CoreFoundation/CFURL.h>
  20. #include <CoreFoundation/CFBundle.h>
  21. #endif
  22. #include <algorithm>
  23. #include <sys/stat.h>
  24. #ifndef S_ISDIR
  25. #define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
  26. #endif
  27. #ifdef BSD4_4
  28. #define stat64 stat
  29. #define fstat64 fstat
  30. #endif
  31. // This namespace has various generic functions related to files and paths.
  32. // The code still needs a ton of cleanup.
  33. // REMEMBER: strdup considered harmful!
  34. namespace FileUtil
  35. {
  36. // Remove any ending forward slashes from directory paths
  37. // Modifies argument.
  38. static void StripTailDirSlashes(std::string &fname)
  39. {
  40. if (fname.length() > 1)
  41. {
  42. size_t i = fname.length() - 1;
  43. while (fname[i] == DIR_SEP_CHR)
  44. fname[i--] = '\0';
  45. }
  46. return;
  47. }
  48. // Returns true if file filename exists
  49. bool Exists(const std::string &filename)
  50. {
  51. struct stat64 file_info;
  52. std::string copy(filename);
  53. StripTailDirSlashes(copy);
  54. #ifdef _WIN32
  55. int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info);
  56. #else
  57. int result = stat64(copy.c_str(), &file_info);
  58. #endif
  59. return (result == 0);
  60. }
  61. // Returns true if filename is a directory
  62. bool IsDirectory(const std::string &filename)
  63. {
  64. struct stat64 file_info;
  65. std::string copy(filename);
  66. StripTailDirSlashes(copy);
  67. #ifdef _WIN32
  68. int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info);
  69. #else
  70. int result = stat64(copy.c_str(), &file_info);
  71. #endif
  72. if (result < 0) {
  73. WARN_LOG(COMMON, "IsDirectory: stat failed on %s: %s",
  74. filename.c_str(), GetLastErrorMsg());
  75. return false;
  76. }
  77. return S_ISDIR(file_info.st_mode);
  78. }
  79. // Deletes a given filename, return true on success
  80. // Doesn't supports deleting a directory
  81. bool Delete(const std::string &filename)
  82. {
  83. INFO_LOG(COMMON, "Delete: file %s", filename.c_str());
  84. // Return true because we care about the file no
  85. // being there, not the actual delete.
  86. if (!Exists(filename))
  87. {
  88. WARN_LOG(COMMON, "Delete: %s does not exist", filename.c_str());
  89. return true;
  90. }
  91. // We can't delete a directory
  92. if (IsDirectory(filename))
  93. {
  94. WARN_LOG(COMMON, "Delete failed: %s is a directory", filename.c_str());
  95. return false;
  96. }
  97. #ifdef _WIN32
  98. if (!DeleteFile(Common::UTF8ToTStr(filename).c_str()))
  99. {
  100. WARN_LOG(COMMON, "Delete: DeleteFile failed on %s: %s",
  101. filename.c_str(), GetLastErrorMsg());
  102. return false;
  103. }
  104. #else
  105. if (unlink(filename.c_str()) == -1) {
  106. WARN_LOG(COMMON, "Delete: unlink failed on %s: %s",
  107. filename.c_str(), GetLastErrorMsg());
  108. return false;
  109. }
  110. #endif
  111. return true;
  112. }
  113. // Returns true if successful, or path already exists.
  114. bool CreateDir(const std::string &path)
  115. {
  116. INFO_LOG(COMMON, "CreateDir: directory %s", path.c_str());
  117. #ifdef _WIN32
  118. if (::CreateDirectory(Common::UTF8ToTStr(path).c_str(), NULL))
  119. return true;
  120. DWORD error = GetLastError();
  121. if (error == ERROR_ALREADY_EXISTS)
  122. {
  123. WARN_LOG(COMMON, "CreateDir: CreateDirectory failed on %s: already exists", path.c_str());
  124. return true;
  125. }
  126. ERROR_LOG(COMMON, "CreateDir: CreateDirectory failed on %s: %i", path.c_str(), error);
  127. return false;
  128. #else
  129. if (mkdir(path.c_str(), 0755) == 0)
  130. return true;
  131. int err = errno;
  132. if (err == EEXIST)
  133. {
  134. WARN_LOG(COMMON, "CreateDir: mkdir failed on %s: already exists", path.c_str());
  135. return true;
  136. }
  137. ERROR_LOG(COMMON, "CreateDir: mkdir failed on %s: %s", path.c_str(), strerror(err));
  138. return false;
  139. #endif
  140. }
  141. // Creates the full path of fullPath returns true on success
  142. bool CreateFullPath(const std::string &fullPath)
  143. {
  144. int panicCounter = 100;
  145. INFO_LOG(COMMON, "CreateFullPath: path %s", fullPath.c_str());
  146. if (FileUtil::Exists(fullPath))
  147. {
  148. INFO_LOG(COMMON, "CreateFullPath: path exists %s", fullPath.c_str());
  149. return true;
  150. }
  151. size_t position = 0;
  152. while (true)
  153. {
  154. // Find next sub path
  155. position = fullPath.find(DIR_SEP_CHR, position);
  156. // we're done, yay!
  157. if (position == fullPath.npos)
  158. return true;
  159. // Include the '/' so the first call is CreateDir("/") rather than CreateDir("")
  160. std::string const subPath(fullPath.substr(0, position + 1));
  161. if (!FileUtil::IsDirectory(subPath))
  162. FileUtil::CreateDir(subPath);
  163. // A safety check
  164. panicCounter--;
  165. if (panicCounter <= 0)
  166. {
  167. ERROR_LOG(COMMON, "CreateFullPath: directory structure is too deep");
  168. return false;
  169. }
  170. position++;
  171. }
  172. }
  173. // Deletes a directory filename, returns true on success
  174. bool DeleteDir(const std::string &filename)
  175. {
  176. INFO_LOG(COMMON, "DeleteDir: directory %s", filename.c_str());
  177. // check if a directory
  178. if (!FileUtil::IsDirectory(filename))
  179. {
  180. ERROR_LOG(COMMON, "DeleteDir: Not a directory %s", filename.c_str());
  181. return false;
  182. }
  183. #ifdef _WIN32
  184. if (::RemoveDirectory(Common::UTF8ToTStr(filename).c_str()))
  185. return true;
  186. #else
  187. if (rmdir(filename.c_str()) == 0)
  188. return true;
  189. #endif
  190. ERROR_LOG(COMMON, "DeleteDir: %s: %s", filename.c_str(), GetLastErrorMsg());
  191. return false;
  192. }
  193. // renames file srcFilename to destFilename, returns true on success
  194. bool Rename(const std::string &srcFilename, const std::string &destFilename)
  195. {
  196. INFO_LOG(COMMON, "Rename: %s --> %s",
  197. srcFilename.c_str(), destFilename.c_str());
  198. if (rename(srcFilename.c_str(), destFilename.c_str()) == 0)
  199. return true;
  200. ERROR_LOG(COMMON, "Rename: failed %s --> %s: %s",
  201. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  202. return false;
  203. }
  204. // copies file srcFilename to destFilename, returns true on success
  205. bool Copy(const std::string &srcFilename, const std::string &destFilename)
  206. {
  207. INFO_LOG(COMMON, "Copy: %s --> %s",
  208. srcFilename.c_str(), destFilename.c_str());
  209. #ifdef _WIN32
  210. if (CopyFile(Common::UTF8ToTStr(srcFilename).c_str(), Common::UTF8ToTStr(destFilename).c_str(), FALSE))
  211. return true;
  212. ERROR_LOG(COMMON, "Copy: failed %s --> %s: %s",
  213. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  214. return false;
  215. #else
  216. // buffer size
  217. #define BSIZE 1024
  218. char buffer[BSIZE];
  219. // Open input file
  220. FILE *input = fopen(srcFilename.c_str(), "rb");
  221. if (!input)
  222. {
  223. ERROR_LOG(COMMON, "Copy: input failed %s --> %s: %s",
  224. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  225. return false;
  226. }
  227. // open output file
  228. FILE *output = fopen(destFilename.c_str(), "wb");
  229. if (!output)
  230. {
  231. fclose(input);
  232. ERROR_LOG(COMMON, "Copy: output failed %s --> %s: %s",
  233. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  234. return false;
  235. }
  236. // copy loop
  237. while (!feof(input))
  238. {
  239. // read input
  240. int rnum = fread(buffer, sizeof(char), BSIZE, input);
  241. if (rnum != BSIZE)
  242. {
  243. if (ferror(input) != 0)
  244. {
  245. ERROR_LOG(COMMON,
  246. "Copy: failed reading from source, %s --> %s: %s",
  247. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  248. goto bail;
  249. }
  250. }
  251. // write output
  252. int wnum = fwrite(buffer, sizeof(char), rnum, output);
  253. if (wnum != rnum)
  254. {
  255. ERROR_LOG(COMMON,
  256. "Copy: failed writing to output, %s --> %s: %s",
  257. srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg());
  258. goto bail;
  259. }
  260. }
  261. // close files
  262. fclose(input);
  263. fclose(output);
  264. return true;
  265. bail:
  266. if (input)
  267. fclose(input);
  268. if (output)
  269. fclose(output);
  270. return false;
  271. #endif
  272. }
  273. // Returns the size of filename (64bit)
  274. u64 GetSize(const std::string &filename)
  275. {
  276. if (!Exists(filename))
  277. {
  278. WARN_LOG(COMMON, "GetSize: failed %s: No such file", filename.c_str());
  279. return 0;
  280. }
  281. if (IsDirectory(filename))
  282. {
  283. WARN_LOG(COMMON, "GetSize: failed %s: is a directory", filename.c_str());
  284. return 0;
  285. }
  286. struct stat64 buf;
  287. #ifdef _WIN32
  288. if (_tstat64(Common::UTF8ToTStr(filename).c_str(), &buf) == 0)
  289. #else
  290. if (stat64(filename.c_str(), &buf) == 0)
  291. #endif
  292. {
  293. DEBUG_LOG(COMMON, "GetSize: %s: %lld",
  294. filename.c_str(), (long long)buf.st_size);
  295. return buf.st_size;
  296. }
  297. ERROR_LOG(COMMON, "GetSize: Stat failed %s: %s",
  298. filename.c_str(), GetLastErrorMsg());
  299. return 0;
  300. }
  301. // Overloaded GetSize, accepts file descriptor
  302. u64 GetSize(const int fd)
  303. {
  304. struct stat64 buf;
  305. if (fstat64(fd, &buf) != 0) {
  306. ERROR_LOG(COMMON, "GetSize: stat failed %i: %s",
  307. fd, GetLastErrorMsg());
  308. return 0;
  309. }
  310. return buf.st_size;
  311. }
  312. // Overloaded GetSize, accepts FILE*
  313. u64 GetSize(FILE *f)
  314. {
  315. // can't use off_t here because it can be 32-bit
  316. u64 pos = ftello(f);
  317. if (fseeko(f, 0, SEEK_END) != 0) {
  318. ERROR_LOG(COMMON, "GetSize: seek failed %p: %s",
  319. f, GetLastErrorMsg());
  320. return 0;
  321. }
  322. u64 size = ftello(f);
  323. if ((size != pos) && (fseeko(f, pos, SEEK_SET) != 0)) {
  324. ERROR_LOG(COMMON, "GetSize: seek failed %p: %s",
  325. f, GetLastErrorMsg());
  326. return 0;
  327. }
  328. return size;
  329. }
  330. // creates an empty file filename, returns true on success
  331. bool CreateEmptyFile(const std::string &filename)
  332. {
  333. INFO_LOG(COMMON, "CreateEmptyFile: %s", filename.c_str());
  334. if (!FileUtil::IOFile(filename, "wb"))
  335. {
  336. ERROR_LOG(COMMON, "CreateEmptyFile: failed %s: %s",
  337. filename.c_str(), GetLastErrorMsg());
  338. return false;
  339. }
  340. return true;
  341. }
  342. // Scans the directory tree gets, starting from _Directory and adds the
  343. // results into parentEntry. Returns the number of files+directories found
  344. u32 ScanDirectoryTree(const std::string &directory, FSTEntry& parentEntry)
  345. {
  346. INFO_LOG(COMMON, "ScanDirectoryTree: directory %s", directory.c_str());
  347. // How many files + directories we found
  348. u32 foundEntries = 0;
  349. #ifdef _WIN32
  350. // Find the first file in the directory.
  351. WIN32_FIND_DATA ffd;
  352. HANDLE hFind = FindFirstFile(Common::UTF8ToTStr(directory + "\\*").c_str(), &ffd);
  353. if (hFind == INVALID_HANDLE_VALUE)
  354. {
  355. FindClose(hFind);
  356. return foundEntries;
  357. }
  358. // windows loop
  359. do
  360. {
  361. FSTEntry entry;
  362. const std::string virtualName(Common::TStrToUTF8(ffd.cFileName));
  363. #else
  364. struct dirent dirent, *result = NULL;
  365. DIR *dirp = opendir(directory.c_str());
  366. if (!dirp)
  367. return 0;
  368. // non windows loop
  369. while (!readdir_r(dirp, &dirent, &result) && result)
  370. {
  371. FSTEntry entry;
  372. const std::string virtualName(result->d_name);
  373. #endif
  374. // check for "." and ".."
  375. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  376. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  377. (virtualName[2] == '\0')))
  378. continue;
  379. entry.virtualName = virtualName;
  380. entry.physicalName = directory;
  381. entry.physicalName += DIR_SEP + entry.virtualName;
  382. if (IsDirectory(entry.physicalName.c_str()))
  383. {
  384. entry.isDirectory = true;
  385. // is a directory, lets go inside
  386. entry.size = ScanDirectoryTree(entry.physicalName, entry);
  387. foundEntries += (u32)entry.size;
  388. }
  389. else
  390. { // is a file
  391. entry.isDirectory = false;
  392. entry.size = GetSize(entry.physicalName.c_str());
  393. }
  394. ++foundEntries;
  395. // Push into the tree
  396. parentEntry.children.push_back(entry);
  397. #ifdef _WIN32
  398. } while (FindNextFile(hFind, &ffd) != 0);
  399. FindClose(hFind);
  400. #else
  401. }
  402. closedir(dirp);
  403. #endif
  404. // Return number of entries found.
  405. return foundEntries;
  406. }
  407. // Deletes the given directory and anything under it. Returns true on success.
  408. bool DeleteDirRecursively(const std::string &directory)
  409. {
  410. INFO_LOG(COMMON, "DeleteDirRecursively: %s", directory.c_str());
  411. #ifdef _WIN32
  412. // Find the first file in the directory.
  413. WIN32_FIND_DATA ffd;
  414. HANDLE hFind = FindFirstFile(Common::UTF8ToTStr(directory + "\\*").c_str(), &ffd);
  415. if (hFind == INVALID_HANDLE_VALUE)
  416. {
  417. FindClose(hFind);
  418. return false;
  419. }
  420. // windows loop
  421. do
  422. {
  423. const std::string virtualName(Common::TStrToUTF8(ffd.cFileName));
  424. #else
  425. struct dirent dirent, *result = NULL;
  426. DIR *dirp = opendir(directory.c_str());
  427. if (!dirp)
  428. return false;
  429. // non windows loop
  430. while (!readdir_r(dirp, &dirent, &result) && result)
  431. {
  432. const std::string virtualName = result->d_name;
  433. #endif
  434. // check for "." and ".."
  435. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  436. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  437. (virtualName[2] == '\0')))
  438. continue;
  439. std::string newPath = directory + DIR_SEP_CHR + virtualName;
  440. if (IsDirectory(newPath))
  441. {
  442. if (!DeleteDirRecursively(newPath))
  443. {
  444. #ifndef _WIN32
  445. closedir(dirp);
  446. #endif
  447. return false;
  448. }
  449. }
  450. else
  451. {
  452. if (!FileUtil::Delete(newPath))
  453. {
  454. #ifndef _WIN32
  455. closedir(dirp);
  456. #endif
  457. return false;
  458. }
  459. }
  460. #ifdef _WIN32
  461. } while (FindNextFile(hFind, &ffd) != 0);
  462. FindClose(hFind);
  463. #else
  464. }
  465. closedir(dirp);
  466. #endif
  467. FileUtil::DeleteDir(directory);
  468. return true;
  469. }
  470. // Create directory and copy contents (does not overwrite existing files)
  471. void CopyDir(const std::string &source_path, const std::string &dest_path)
  472. {
  473. #ifndef _WIN32
  474. if (source_path == dest_path) return;
  475. if (!FileUtil::Exists(source_path)) return;
  476. if (!FileUtil::Exists(dest_path)) FileUtil::CreateFullPath(dest_path);
  477. struct dirent dirent, *result = NULL;
  478. DIR *dirp = opendir(source_path.c_str());
  479. if (!dirp) return;
  480. while (!readdir_r(dirp, &dirent, &result) && result)
  481. {
  482. const std::string virtualName(result->d_name);
  483. // check for "." and ".."
  484. if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
  485. ((virtualName[0] == '.') && (virtualName[1] == '.') &&
  486. (virtualName[2] == '\0')))
  487. continue;
  488. std::string source, dest;
  489. source = source_path + virtualName;
  490. dest = dest_path + virtualName;
  491. if (IsDirectory(source))
  492. {
  493. source += '/';
  494. dest += '/';
  495. if (!FileUtil::Exists(dest)) FileUtil::CreateFullPath(dest);
  496. CopyDir(source, dest);
  497. }
  498. else if (!FileUtil::Exists(dest)) FileUtil::Copy(source, dest);
  499. }
  500. closedir(dirp);
  501. #endif
  502. }
  503. // Returns the current directory
  504. std::string GetCurrentDir()
  505. {
  506. char *dir;
  507. // Get the current working directory (getcwd uses malloc)
  508. if (!(dir = __getcwd(NULL, 0))) {
  509. ERROR_LOG(COMMON, "GetCurrentDirectory failed: %s",
  510. GetLastErrorMsg());
  511. return NULL;
  512. }
  513. std::string strDir = dir;
  514. free(dir);
  515. return strDir;
  516. }
  517. // Sets the current directory to the given directory
  518. bool SetCurrentDir(const std::string &directory)
  519. {
  520. return __chdir(directory.c_str()) == 0;
  521. }
  522. #if defined(__APPLE__)
  523. std::string GetBundleDirectory()
  524. {
  525. CFURLRef BundleRef;
  526. char AppBundlePath[MAXPATHLEN];
  527. // Get the main bundle for the app
  528. BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  529. CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
  530. CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
  531. CFRelease(BundleRef);
  532. CFRelease(BundlePath);
  533. return AppBundlePath;
  534. }
  535. #endif
  536. #ifdef _WIN32
  537. std::string& GetExeDirectory()
  538. {
  539. static std::string DolphinPath;
  540. if (DolphinPath.empty())
  541. {
  542. TCHAR Dolphin_exe_Path[2048];
  543. GetModuleFileName(NULL, Dolphin_exe_Path, 2048);
  544. DolphinPath = Common::TStrToUTF8(Dolphin_exe_Path);
  545. DolphinPath = DolphinPath.substr(0, DolphinPath.find_last_of('\\'));
  546. }
  547. return DolphinPath;
  548. }
  549. #endif
  550. std::string GetSysDirectory()
  551. {
  552. std::string sysDir;
  553. #if defined (__APPLE__)
  554. sysDir = GetBundleDirectory();
  555. sysDir += DIR_SEP;
  556. sysDir += SYSDATA_DIR;
  557. #else
  558. sysDir = SYSDATA_DIR;
  559. #endif
  560. sysDir += DIR_SEP;
  561. INFO_LOG(COMMON, "GetSysDirectory: Setting to %s:", sysDir.c_str());
  562. return sysDir;
  563. }
  564. // Returns a string with a Dolphin data dir or file in the user's home
  565. // directory. To be used in "multi-user" mode (that is, installed).
  566. const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath)
  567. {
  568. static std::string paths[NUM_PATH_INDICES];
  569. // Set up all paths and files on the first run
  570. if (paths[D_USER_IDX].empty())
  571. {
  572. #ifdef _WIN32
  573. paths[D_USER_IDX] = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
  574. #else
  575. if (FileUtil::Exists(ROOT_DIR DIR_SEP USERDATA_DIR))
  576. paths[D_USER_IDX] = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
  577. else
  578. paths[D_USER_IDX] = std::string(getenv("HOME") ?
  579. getenv("HOME") : getenv("PWD") ?
  580. getenv("PWD") : "") + DIR_SEP EMU_DATA_DIR DIR_SEP;
  581. #endif
  582. paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
  583. paths[D_GAMECONFIG_IDX] = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
  584. paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
  585. paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
  586. paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
  587. paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
  588. paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
  589. paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
  590. paths[D_SCREENSHOTS_IDX] = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
  591. paths[D_DUMP_IDX] = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
  592. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  593. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  594. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  595. paths[D_LOGS_IDX] = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
  596. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  597. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  598. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  599. }
  600. if (!newPath.empty())
  601. {
  602. if (!FileUtil::IsDirectory(newPath))
  603. {
  604. WARN_LOG(COMMON, "Invalid path specified %s", newPath.c_str());
  605. return paths[DirIDX];
  606. }
  607. else
  608. {
  609. paths[DirIDX] = newPath;
  610. }
  611. switch (DirIDX)
  612. {
  613. case D_ROOT_IDX:
  614. paths[D_USER_IDX] = paths[D_ROOT_IDX] + DIR_SEP;
  615. paths[D_SYSCONF_IDX] = paths[D_USER_IDX] + SYSCONF_DIR + DIR_SEP;
  616. paths[F_SYSCONF_IDX] = paths[D_SYSCONF_IDX] + SYSCONF;
  617. break;
  618. case D_USER_IDX:
  619. paths[D_USER_IDX] = paths[D_ROOT_IDX] + DIR_SEP;
  620. paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
  621. paths[D_GAMECONFIG_IDX] = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
  622. paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
  623. paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
  624. paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
  625. paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
  626. paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
  627. paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
  628. paths[D_SCREENSHOTS_IDX] = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
  629. paths[D_DUMP_IDX] = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
  630. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  631. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  632. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  633. paths[D_LOGS_IDX] = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
  634. paths[D_SYSCONF_IDX] = paths[D_USER_IDX] + SYSCONF_DIR DIR_SEP;
  635. paths[F_EMUCONFIG_IDX] = paths[D_CONFIG_IDX] + EMU_CONFIG;
  636. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  637. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  638. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  639. break;
  640. case D_CONFIG_IDX:
  641. paths[F_EMUCONFIG_IDX] = paths[D_CONFIG_IDX] + EMU_CONFIG;
  642. paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
  643. paths[F_LOGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
  644. break;
  645. case D_DUMP_IDX:
  646. paths[D_DUMPFRAMES_IDX] = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
  647. paths[D_DUMPAUDIO_IDX] = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
  648. paths[D_DUMPTEXTURES_IDX] = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
  649. break;
  650. case D_LOGS_IDX:
  651. paths[F_MAINLOG_IDX] = paths[D_LOGS_IDX] + MAIN_LOG;
  652. }
  653. }
  654. return paths[DirIDX];
  655. }
  656. //std::string GetThemeDir(const std::string& theme_name)
  657. //{
  658. // std::string dir = FileUtil::GetUserPath(D_THEMES_IDX) + theme_name + "/";
  659. //
  660. //#if !defined(_WIN32)
  661. // // If theme does not exist in user's dir load from shared directory
  662. // if (!FileUtil::Exists(dir))
  663. // dir = SHARED_USER_DIR THEMES_DIR "/" + theme_name + "/";
  664. //#endif
  665. //
  666. // return dir;
  667. //}
  668. size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename)
  669. {
  670. return FileUtil::IOFile(filename, text_file ? "w" : "wb").WriteBytes(str.data(), str.size());
  671. }
  672. size_t ReadFileToString(bool text_file, const char *filename, std::string &str)
  673. {
  674. FileUtil::IOFile file(filename, text_file ? "r" : "rb");
  675. auto const f = file.GetHandle();
  676. if (!f)
  677. return false;
  678. str.resize(static_cast<u32>(GetSize(f)));
  679. return file.ReadArray(&str[0], str.size());
  680. }
  681. /**
  682. * Splits the filename into 8.3 format
  683. * Loosely implemented following https://en.wikipedia.org/wiki/8.3_filename
  684. * @param filename The normal filename to use
  685. * @param short_name A 9-char array in which the short name will be written
  686. * @param extension A 4-char array in which the extension will be written
  687. */
  688. void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
  689. std::array<char, 4>& extension) {
  690. const std::string forbidden_characters = ".\"/\\[]:;=, ";
  691. // On a FAT32 partition, 8.3 names are stored as a 11 bytes array, filled with spaces.
  692. short_name = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
  693. extension = {' ', ' ', ' ', '\0'};
  694. std::string::size_type point = filename.rfind('.');
  695. if (point == filename.size() - 1)
  696. point = filename.rfind('.', point);
  697. // Get short name.
  698. int j = 0;
  699. for (char letter : filename.substr(0, point)) {
  700. if (forbidden_characters.find(letter, 0) != std::string::npos)
  701. continue;
  702. if (j == 8) {
  703. // TODO(Link Mauve): also do that for filenames containing a space.
  704. // TODO(Link Mauve): handle multiple files having the same short name.
  705. short_name[6] = '~';
  706. short_name[7] = '1';
  707. break;
  708. }
  709. short_name[j++] = toupper(letter);
  710. }
  711. // Get extension.
  712. if (point != std::string::npos) {
  713. j = 0;
  714. for (char letter : filename.substr(point + 1, 3))
  715. extension[j++] = toupper(letter);
  716. }
  717. }
  718. IOFile::IOFile()
  719. : m_file(NULL), m_good(true)
  720. {}
  721. IOFile::IOFile(std::FILE* file)
  722. : m_file(file), m_good(true)
  723. {}
  724. IOFile::IOFile(const std::string& filename, const char openmode[])
  725. : m_file(NULL), m_good(true)
  726. {
  727. Open(filename, openmode);
  728. }
  729. IOFile::~IOFile()
  730. {
  731. Close();
  732. }
  733. IOFile::IOFile(IOFile&& other)
  734. : m_file(NULL), m_good(true)
  735. {
  736. Swap(other);
  737. }
  738. IOFile& IOFile::operator=(IOFile&& other)
  739. {
  740. Swap(other);
  741. return *this;
  742. }
  743. void IOFile::Swap(IOFile& other)
  744. {
  745. std::swap(m_file, other.m_file);
  746. std::swap(m_good, other.m_good);
  747. }
  748. bool IOFile::Open(const std::string& filename, const char openmode[])
  749. {
  750. Close();
  751. #ifdef _WIN32
  752. _tfopen_s(&m_file, Common::UTF8ToTStr(filename).c_str(), Common::UTF8ToTStr(openmode).c_str());
  753. #else
  754. m_file = fopen(filename.c_str(), openmode);
  755. #endif
  756. m_good = IsOpen();
  757. return m_good;
  758. }
  759. bool IOFile::Close()
  760. {
  761. if (!IsOpen() || 0 != std::fclose(m_file))
  762. m_good = false;
  763. m_file = NULL;
  764. return m_good;
  765. }
  766. std::FILE* IOFile::ReleaseHandle()
  767. {
  768. std::FILE* const ret = m_file;
  769. m_file = NULL;
  770. return ret;
  771. }
  772. void IOFile::SetHandle(std::FILE* file)
  773. {
  774. Close();
  775. Clear();
  776. m_file = file;
  777. }
  778. u64 IOFile::GetSize()
  779. {
  780. if (IsOpen())
  781. return FileUtil::GetSize(m_file);
  782. else
  783. return 0;
  784. }
  785. bool IOFile::Seek(s64 off, int origin)
  786. {
  787. if (!IsOpen() || 0 != fseeko(m_file, off, origin))
  788. m_good = false;
  789. return m_good;
  790. }
  791. u64 IOFile::Tell()
  792. {
  793. if (IsOpen())
  794. return ftello(m_file);
  795. else
  796. return -1;
  797. }
  798. bool IOFile::Flush()
  799. {
  800. if (!IsOpen() || 0 != std::fflush(m_file))
  801. m_good = false;
  802. return m_good;
  803. }
  804. bool IOFile::Resize(u64 size)
  805. {
  806. if (!IsOpen() || 0 !=
  807. #ifdef _WIN32
  808. // ector: _chsize sucks, not 64-bit safe
  809. // F|RES: changed to _chsize_s. i think it is 64-bit safe
  810. _chsize_s(_fileno(m_file), size)
  811. #else
  812. // TODO: handle 64bit and growing
  813. ftruncate(fileno(m_file), size)
  814. #endif
  815. )
  816. m_good = false;
  817. return m_good;
  818. }
  819. } // namespace