file_util.h 8.5 KB

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