file_util.h 10 KB

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