file_util.h 9.8 KB

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