file_util.h 9.0 KB

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