file_util.h 9.8 KB

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