file_util.h 9.3 KB

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