file_util.h 9.8 KB

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