file_util.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #pragma once
  5. #include <array>
  6. #include <fstream>
  7. #include <functional>
  8. #include <cstdio>
  9. #include <string>
  10. #include <type_traits>
  11. #include <vector>
  12. #include "common/common_types.h"
  13. #ifdef _MSC_VER
  14. #include "common/string_util.h"
  15. #endif
  16. // User directory indices for GetUserPath
  17. enum {
  18. D_USER_IDX,
  19. D_ROOT_IDX,
  20. D_CONFIG_IDX,
  21. D_GAMECONFIG_IDX,
  22. D_MAPS_IDX,
  23. D_CACHE_IDX,
  24. D_SHADERCACHE_IDX,
  25. D_SHADERS_IDX,
  26. D_STATESAVES_IDX,
  27. D_SCREENSHOTS_IDX,
  28. D_SDMC_IDX,
  29. D_NAND_IDX,
  30. D_SYSDATA_IDX,
  31. D_HIRESTEXTURES_IDX,
  32. D_DUMP_IDX,
  33. D_DUMPFRAMES_IDX,
  34. D_DUMPAUDIO_IDX,
  35. D_DUMPTEXTURES_IDX,
  36. D_DUMPDSP_IDX,
  37. D_LOGS_IDX,
  38. D_SYSCONF_IDX,
  39. F_EMUCONFIG_IDX,
  40. F_DEBUGGERCONFIG_IDX,
  41. F_LOGGERCONFIG_IDX,
  42. F_MAINLOG_IDX,
  43. F_RAMDUMP_IDX,
  44. F_ARAMDUMP_IDX,
  45. F_SYSCONF_IDX,
  46. NUM_PATH_INDICES
  47. };
  48. namespace FileUtil
  49. {
  50. // FileSystem tree node/
  51. struct FSTEntry
  52. {
  53. bool isDirectory;
  54. u64 size; // file length or number of entries from children
  55. std::string physicalName; // name on disk
  56. std::string virtualName; // name in FST names table
  57. std::vector<FSTEntry> children;
  58. };
  59. // Returns true if file filename exists
  60. bool Exists(const std::string &filename);
  61. // Returns true if filename is a directory
  62. bool IsDirectory(const std::string &filename);
  63. // Returns the size of filename (64bit)
  64. u64 GetSize(const std::string &filename);
  65. // Overloaded GetSize, accepts file descriptor
  66. u64 GetSize(const int fd);
  67. // Overloaded GetSize, accepts FILE*
  68. u64 GetSize(FILE *f);
  69. // Returns true if successful, or path already exists.
  70. bool CreateDir(const std::string &filename);
  71. // Creates the full path of fullPath returns true on success
  72. bool CreateFullPath(const std::string &fullPath);
  73. // Deletes a given filename, return true on success
  74. // Doesn't supports deleting a directory
  75. bool Delete(const std::string &filename);
  76. // Deletes a directory filename, returns true on success
  77. bool DeleteDir(const std::string &filename);
  78. // renames file srcFilename to destFilename, returns true on success
  79. bool Rename(const std::string &srcFilename, const std::string &destFilename);
  80. // copies file srcFilename to destFilename, returns true on success
  81. bool Copy(const std::string &srcFilename, const std::string &destFilename);
  82. // creates an empty file filename, returns true on success
  83. bool CreateEmptyFile(const std::string &filename);
  84. /**
  85. * @param num_entries_out to be assigned by the callable with the number of iterated directory entries, never null
  86. * @param directory the path to the enclosing directory
  87. * @param virtual_name the entry name, without any preceding directory info
  88. * @return whether handling the entry succeeded
  89. */
  90. using DirectoryEntryCallable = std::function<bool(unsigned* num_entries_out,
  91. const std::string& directory,
  92. const std::string& virtual_name)>;
  93. /**
  94. * Scans a directory, calling the callback for each file/directory contained within.
  95. * If the callback returns failure, scanning halts and this function returns failure as well
  96. * @param num_entries_out assigned by the function with the number of iterated directory entries, can be null
  97. * @param directory the directory to scan
  98. * @param callback The callback which will be called for each entry
  99. * @return whether scanning the directory succeeded
  100. */
  101. bool ForeachDirectoryEntry(unsigned* num_entries_out, const std::string &directory, DirectoryEntryCallable callback);
  102. /**
  103. * Scans the directory tree, storing the results.
  104. * @param directory the parent directory to start scanning from
  105. * @param parent_entry FSTEntry where the filesystem tree results will be stored.
  106. * @param recursion Number of children directories to read before giving up.
  107. * @return the total number of files/directories found
  108. */
  109. unsigned ScanDirectoryTree(const std::string &directory, FSTEntry& parent_entry, unsigned int recursion = 0);
  110. // deletes the given directory and anything under it. Returns true on success.
  111. bool DeleteDirRecursively(const std::string &directory, unsigned int recursion = 256);
  112. // Returns the current directory
  113. std::string GetCurrentDir();
  114. // Create directory and copy contents (does not overwrite existing files)
  115. void CopyDir(const std::string &source_path, const std::string &dest_path);
  116. // Set the current directory to given directory
  117. bool SetCurrentDir(const std::string &directory);
  118. // Returns a pointer to a string with a Citra data dir in the user's home
  119. // directory. To be used in "multi-user" mode (that is, installed).
  120. const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath="");
  121. // Returns the path to where the sys file are
  122. std::string GetSysDirectory();
  123. #ifdef __APPLE__
  124. std::string GetBundleDirectory();
  125. #endif
  126. #ifdef _WIN32
  127. std::string &GetExeDirectory();
  128. #endif
  129. size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename);
  130. size_t ReadFileToString(bool text_file, const char *filename, std::string &str);
  131. /**
  132. * Splits the filename into 8.3 format
  133. * Loosely implemented following https://en.wikipedia.org/wiki/8.3_filename
  134. * @param filename The normal filename to use
  135. * @param short_name A 9-char array in which the short name will be written
  136. * @param extension A 4-char array in which the extension will be written
  137. */
  138. void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
  139. std::array<char, 4>& extension);
  140. // simple wrapper for cstdlib file functions to
  141. // hopefully will make error checking easier
  142. // and make forgetting an fclose() harder
  143. class IOFile : public NonCopyable
  144. {
  145. public:
  146. IOFile();
  147. IOFile(const std::string& filename, const char openmode[]);
  148. ~IOFile();
  149. IOFile(IOFile&& other);
  150. IOFile& operator=(IOFile&& other);
  151. void Swap(IOFile& other);
  152. bool Open(const std::string& filename, const char openmode[]);
  153. bool Close();
  154. template <typename T>
  155. size_t ReadArray(T* data, size_t length)
  156. {
  157. static_assert(std::is_standard_layout<T>(), "Given array does not consist of standard layout objects");
  158. #if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER)
  159. static_assert(std::is_trivially_copyable<T>(), "Given array does not consist of trivially copyable objects");
  160. #endif
  161. if (!IsOpen()) {
  162. m_good = false;
  163. return -1;
  164. }
  165. size_t items_read = std::fread(data, sizeof(T), length, m_file);
  166. if (items_read != length)
  167. m_good = false;
  168. return items_read;
  169. }
  170. template <typename T>
  171. size_t WriteArray(const T* data, size_t length)
  172. {
  173. static_assert(std::is_standard_layout<T>(), "Given array does not consist of standard layout objects");
  174. #if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER)
  175. static_assert(std::is_trivially_copyable<T>(), "Given array does not consist of trivially copyable objects");
  176. #endif
  177. if (!IsOpen()) {
  178. m_good = false;
  179. return -1;
  180. }
  181. size_t items_written = std::fwrite(data, sizeof(T), length, m_file);
  182. if (items_written != length)
  183. m_good = false;
  184. return items_written;
  185. }
  186. size_t ReadBytes(void* data, size_t length)
  187. {
  188. return ReadArray(reinterpret_cast<char*>(data), length);
  189. }
  190. size_t WriteBytes(const void* data, size_t length)
  191. {
  192. return WriteArray(reinterpret_cast<const char*>(data), length);
  193. }
  194. template<typename T>
  195. size_t WriteObject(const T& object) {
  196. static_assert(!std::is_pointer<T>::value, "Given object is a pointer");
  197. return WriteArray(&object, 1);
  198. }
  199. bool IsOpen() const { return nullptr != m_file; }
  200. // m_good is set to false when a read, write or other function fails
  201. bool IsGood() const { return m_good; }
  202. explicit operator bool() const { return IsGood(); }
  203. bool Seek(s64 off, int origin);
  204. u64 Tell() const;
  205. u64 GetSize() const;
  206. bool Resize(u64 size);
  207. bool Flush();
  208. // clear error state
  209. void Clear() { m_good = true; std::clearerr(m_file); }
  210. private:
  211. std::FILE* m_file = nullptr;
  212. bool m_good = true;
  213. };
  214. } // namespace
  215. // To deal with Windows being dumb at unicode:
  216. template <typename T>
  217. void OpenFStream(T& fstream, const std::string& filename, std::ios_base::openmode openmode)
  218. {
  219. #ifdef _MSC_VER
  220. fstream.open(Common::UTF8ToTStr(filename).c_str(), openmode);
  221. #else
  222. fstream.open(filename.c_str(), openmode);
  223. #endif
  224. }