file_util.h 9.3 KB

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