file.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <cstdio>
  6. #include <filesystem>
  7. #include <fstream>
  8. #include <span>
  9. #include <type_traits>
  10. #include <vector>
  11. #include "common/concepts.h"
  12. #include "common/fs/fs_types.h"
  13. #include "common/fs/fs_util.h"
  14. namespace Common::FS {
  15. enum class SeekOrigin {
  16. SetOrigin, // Seeks from the start of the file.
  17. CurrentPosition, // Seeks from the current file pointer position.
  18. End, // Seeks from the end of the file.
  19. };
  20. /**
  21. * Opens a file stream at path with the specified open mode.
  22. *
  23. * @param file_stream Reference to file stream
  24. * @param path Filesystem path
  25. * @param open_mode File stream open mode
  26. */
  27. template <typename FileStream>
  28. void OpenFileStream(FileStream& file_stream, const std::filesystem::path& path,
  29. std::ios_base::openmode open_mode) {
  30. file_stream.open(path, open_mode);
  31. }
  32. #ifdef _WIN32
  33. template <typename FileStream, typename Path>
  34. void OpenFileStream(FileStream& file_stream, const Path& path, std::ios_base::openmode open_mode) {
  35. if constexpr (IsChar<typename Path::value_type>) {
  36. file_stream.open(ToU8String(path), open_mode);
  37. } else {
  38. file_stream.open(std::filesystem::path{path}, open_mode);
  39. }
  40. }
  41. #endif
  42. /**
  43. * Reads an entire file at path and returns a string of the contents read from the file.
  44. * If the filesystem object at path is not a file, this function returns an empty string.
  45. *
  46. * @param path Filesystem path
  47. * @param type File type
  48. *
  49. * @returns A string of the contents read from the file.
  50. */
  51. [[nodiscard]] std::string ReadStringFromFile(const std::filesystem::path& path, FileType type);
  52. #ifdef _WIN32
  53. template <typename Path>
  54. [[nodiscard]] std::string ReadStringFromFile(const Path& path, FileType type) {
  55. if constexpr (IsChar<typename Path::value_type>) {
  56. return ReadStringFromFile(ToU8String(path), type);
  57. } else {
  58. return ReadStringFromFile(std::filesystem::path{path}, type);
  59. }
  60. }
  61. #endif
  62. /**
  63. * Writes a string to a file at path and returns the number of characters successfully written.
  64. * If a file already exists at path, its contents will be erased.
  65. * If the filesystem object at path is not a file, this function returns 0.
  66. *
  67. * @param path Filesystem path
  68. * @param type File type
  69. *
  70. * @returns Number of characters successfully written.
  71. */
  72. [[nodiscard]] size_t WriteStringToFile(const std::filesystem::path& path, FileType type,
  73. std::string_view string);
  74. #ifdef _WIN32
  75. template <typename Path>
  76. [[nodiscard]] size_t WriteStringToFile(const Path& path, FileType type, std::string_view string) {
  77. if constexpr (IsChar<typename Path::value_type>) {
  78. return WriteStringToFile(ToU8String(path), type, string);
  79. } else {
  80. return WriteStringToFile(std::filesystem::path{path}, type, string);
  81. }
  82. }
  83. #endif
  84. /**
  85. * Appends a string to a file at path and returns the number of characters successfully written.
  86. * If the filesystem object at path is not a file, this function returns 0.
  87. *
  88. * @param path Filesystem path
  89. * @param type File type
  90. *
  91. * @returns Number of characters successfully written.
  92. */
  93. [[nodiscard]] size_t AppendStringToFile(const std::filesystem::path& path, FileType type,
  94. std::string_view string);
  95. #ifdef _WIN32
  96. template <typename Path>
  97. [[nodiscard]] size_t AppendStringToFile(const Path& path, FileType type, std::string_view string) {
  98. if constexpr (IsChar<typename Path::value_type>) {
  99. return AppendStringToFile(ToU8String(path), type, string);
  100. } else {
  101. return AppendStringToFile(std::filesystem::path{path}, type, string);
  102. }
  103. }
  104. #endif
  105. class IOFile final {
  106. public:
  107. IOFile();
  108. explicit IOFile(const std::string& path, FileAccessMode mode,
  109. FileType type = FileType::BinaryFile,
  110. FileShareFlag flag = FileShareFlag::ShareReadOnly);
  111. explicit IOFile(std::string_view path, FileAccessMode mode,
  112. FileType type = FileType::BinaryFile,
  113. FileShareFlag flag = FileShareFlag::ShareReadOnly);
  114. /**
  115. * An IOFile is a lightweight wrapper on C Library file operations.
  116. * Automatically closes an open file on the destruction of an IOFile object.
  117. *
  118. * @param path Filesystem path
  119. * @param mode File access mode
  120. * @param type File type, default is BinaryFile. Use TextFile to open the file as a text file
  121. * @param flag (Windows only) File-share access flag, default is ShareReadOnly
  122. */
  123. explicit IOFile(const std::filesystem::path& path, FileAccessMode mode,
  124. FileType type = FileType::BinaryFile,
  125. FileShareFlag flag = FileShareFlag::ShareReadOnly);
  126. ~IOFile();
  127. IOFile(const IOFile&) = delete;
  128. IOFile& operator=(const IOFile&) = delete;
  129. IOFile(IOFile&& other) noexcept;
  130. IOFile& operator=(IOFile&& other) noexcept;
  131. /**
  132. * Gets the path of the file.
  133. *
  134. * @returns The path of the file.
  135. */
  136. [[nodiscard]] std::filesystem::path GetPath() const;
  137. /**
  138. * Gets the access mode of the file.
  139. *
  140. * @returns The access mode of the file.
  141. */
  142. [[nodiscard]] FileAccessMode GetAccessMode() const;
  143. /**
  144. * Gets the type of the file.
  145. *
  146. * @returns The type of the file.
  147. */
  148. [[nodiscard]] FileType GetType() const;
  149. /**
  150. * Opens a file at path with the specified file access mode.
  151. * This function behaves differently depending on the FileAccessMode.
  152. * These behaviors are documented in each enum value of FileAccessMode.
  153. *
  154. * @param path Filesystem path
  155. * @param mode File access mode
  156. * @param type File type, default is BinaryFile. Use TextFile to open the file as a text file
  157. * @param flag (Windows only) File-share access flag, default is ShareReadOnly
  158. */
  159. void Open(const std::filesystem::path& path, FileAccessMode mode,
  160. FileType type = FileType::BinaryFile,
  161. FileShareFlag flag = FileShareFlag::ShareReadOnly);
  162. #ifdef _WIN32
  163. template <typename Path>
  164. [[nodiscard]] void Open(const Path& path, FileAccessMode mode,
  165. FileType type = FileType::BinaryFile,
  166. FileShareFlag flag = FileShareFlag::ShareReadOnly) {
  167. using ValueType = typename Path::value_type;
  168. if constexpr (IsChar<ValueType>) {
  169. Open(ToU8String(path), mode, type, flag);
  170. } else {
  171. Open(std::filesystem::path{path}, mode, type, flag);
  172. }
  173. }
  174. #endif
  175. /// Closes the file if it is opened.
  176. void Close();
  177. /**
  178. * Checks whether the file is open.
  179. * Use this to check whether the calls to Open() or Close() succeeded.
  180. *
  181. * @returns True if the file is open, false otherwise.
  182. */
  183. [[nodiscard]] bool IsOpen() const;
  184. /**
  185. * Helper function which deduces the value type of a contiguous STL container used in ReadSpan.
  186. * If T is not a contiguous STL container as defined by the concept IsSTLContainer, this calls
  187. * ReadObject and T must be a trivially copyable object.
  188. *
  189. * See ReadSpan for more details if T is a contiguous container.
  190. * See ReadObject for more details if T is a trivially copyable object.
  191. *
  192. * @tparam T Contiguous container or trivially copyable object
  193. *
  194. * @param data Container of T::value_type data or reference to object
  195. *
  196. * @returns Count of T::value_type data or objects successfully read.
  197. */
  198. template <typename T>
  199. [[nodiscard]] size_t Read(T& data) const {
  200. if constexpr (IsSTLContainer<T>) {
  201. using ContiguousType = typename T::value_type;
  202. static_assert(std::is_trivially_copyable_v<ContiguousType>,
  203. "Data type must be trivially copyable.");
  204. return ReadSpan<ContiguousType>(data);
  205. } else {
  206. return ReadObject(data) ? 1 : 0;
  207. }
  208. }
  209. /**
  210. * Helper function which deduces the value type of a contiguous STL container used in WriteSpan.
  211. * If T is not a contiguous STL container as defined by the concept IsSTLContainer, this calls
  212. * WriteObject and T must be a trivially copyable object.
  213. *
  214. * See WriteSpan for more details if T is a contiguous container.
  215. * See WriteObject for more details if T is a trivially copyable object.
  216. *
  217. * @tparam T Contiguous container or trivially copyable object
  218. *
  219. * @param data Container of T::value_type data or const reference to object
  220. *
  221. * @returns Count of T::value_type data or objects successfully written.
  222. */
  223. template <typename T>
  224. [[nodiscard]] size_t Write(const T& data) const {
  225. if constexpr (IsSTLContainer<T>) {
  226. using ContiguousType = typename T::value_type;
  227. static_assert(std::is_trivially_copyable_v<ContiguousType>,
  228. "Data type must be trivially copyable.");
  229. return WriteSpan<ContiguousType>(data);
  230. } else {
  231. static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
  232. return WriteObject(data) ? 1 : 0;
  233. }
  234. }
  235. /**
  236. * Reads a span of T data from a file sequentially.
  237. * This function reads from the current position of the file pointer and
  238. * advances it by the (count of T * sizeof(T)) bytes successfully read.
  239. *
  240. * Failures occur when:
  241. * - The file is not open
  242. * - The opened file lacks read permissions
  243. * - Attempting to read beyond the end-of-file
  244. *
  245. * @tparam T Data type
  246. *
  247. * @param data Span of T data
  248. *
  249. * @returns Count of T data successfully read.
  250. */
  251. template <typename T>
  252. [[nodiscard]] size_t ReadSpan(std::span<T> data) const {
  253. static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
  254. if (!IsOpen()) {
  255. return 0;
  256. }
  257. return std::fread(data.data(), sizeof(T), data.size(), file);
  258. }
  259. /**
  260. * Writes a span of T data to a file sequentially.
  261. * This function writes from the current position of the file pointer and
  262. * advances it by the (count of T * sizeof(T)) bytes successfully written.
  263. *
  264. * Failures occur when:
  265. * - The file is not open
  266. * - The opened file lacks write permissions
  267. *
  268. * @tparam T Data type
  269. *
  270. * @param data Span of T data
  271. *
  272. * @returns Count of T data successfully written.
  273. */
  274. template <typename T>
  275. [[nodiscard]] size_t WriteSpan(std::span<const T> data) const {
  276. static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
  277. if (!IsOpen()) {
  278. return 0;
  279. }
  280. return std::fwrite(data.data(), sizeof(T), data.size(), file);
  281. }
  282. /**
  283. * Reads a T object from a file sequentially.
  284. * This function reads from the current position of the file pointer and
  285. * advances it by the sizeof(T) bytes successfully read.
  286. *
  287. * Failures occur when:
  288. * - The file is not open
  289. * - The opened file lacks read permissions
  290. * - Attempting to read beyond the end-of-file
  291. *
  292. * @tparam T Data type
  293. *
  294. * @param object Reference to object
  295. *
  296. * @returns True if the object is successfully read from the file, false otherwise.
  297. */
  298. template <typename T>
  299. [[nodiscard]] bool ReadObject(T& object) const {
  300. static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
  301. static_assert(!std::is_pointer_v<T>, "T must not be a pointer to an object.");
  302. if (!IsOpen()) {
  303. return false;
  304. }
  305. return std::fread(&object, sizeof(T), 1, file) == 1;
  306. }
  307. /**
  308. * Writes a T object to a file sequentially.
  309. * This function writes from the current position of the file pointer and
  310. * advances it by the sizeof(T) bytes successfully written.
  311. *
  312. * Failures occur when:
  313. * - The file is not open
  314. * - The opened file lacks write permissions
  315. *
  316. * @tparam T Data type
  317. *
  318. * @param object Const reference to object
  319. *
  320. * @returns True if the object is successfully written to the file, false otherwise.
  321. */
  322. template <typename T>
  323. [[nodiscard]] bool WriteObject(const T& object) const {
  324. static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
  325. static_assert(!std::is_pointer_v<T>, "T must not be a pointer to an object.");
  326. if (!IsOpen()) {
  327. return false;
  328. }
  329. return std::fwrite(&object, sizeof(T), 1, file) == 1;
  330. }
  331. /**
  332. * Specialized function to read a string of a given length from a file sequentially.
  333. * This function writes from the current position of the file pointer and
  334. * advances it by the number of characters successfully read.
  335. * The size of the returned string may not match length if not all bytes are successfully read.
  336. *
  337. * @param length Length of the string
  338. *
  339. * @returns A string read from the file.
  340. */
  341. [[nodiscard]] std::string ReadString(size_t length) const;
  342. /**
  343. * Specialized function to write a string to a file sequentially.
  344. * This function writes from the current position of the file pointer and
  345. * advances it by the number of characters successfully written.
  346. *
  347. * @param string Span of const char backed std::string or std::string_view
  348. *
  349. * @returns Number of characters successfully written.
  350. */
  351. [[nodiscard]] size_t WriteString(std::span<const char> string) const;
  352. /**
  353. * Attempts to flush any unwritten buffered data into the file and flush the file into the disk.
  354. *
  355. * @returns True if the flush was successful, false otherwise.
  356. */
  357. bool Flush() const;
  358. /**
  359. * Resizes the file to a given size.
  360. * If the file is resized to a smaller size, the remainder of the file is discarded.
  361. * If the file is resized to a larger size, the new area appears as if zero-filled.
  362. *
  363. * Failures occur when:
  364. * - The file is not open
  365. *
  366. * @param size File size in bytes
  367. *
  368. * @returns True if the file resize succeeded, false otherwise.
  369. */
  370. [[nodiscard]] bool SetSize(u64 size) const;
  371. /**
  372. * Gets the size of the file.
  373. *
  374. * Failures occur when:
  375. * - The file is not open
  376. *
  377. * @returns The file size in bytes of the file. Returns 0 on failure.
  378. */
  379. [[nodiscard]] u64 GetSize() const;
  380. /**
  381. * Moves the current position of the file pointer with the specified offset and seek origin.
  382. *
  383. * @param offset Offset from seek origin
  384. * @param origin Seek origin
  385. *
  386. * @returns True if the file pointer has moved to the specified offset, false otherwise.
  387. */
  388. [[nodiscard]] bool Seek(s64 offset, SeekOrigin origin = SeekOrigin::SetOrigin) const;
  389. /**
  390. * Gets the current position of the file pointer.
  391. *
  392. * @returns The current position of the file pointer.
  393. */
  394. [[nodiscard]] s64 Tell() const;
  395. private:
  396. std::filesystem::path file_path;
  397. FileAccessMode file_access_mode{};
  398. FileType file_type{};
  399. std::FILE* file = nullptr;
  400. };
  401. } // namespace Common::FS