🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

  1. #ifndef AL_FSTREAM_H
  2. #define AL_FSTREAM_H
  3. #ifdef _WIN32
  4. #define WIN32_LEAN_AND_MEAN
  5. #include <windows.h>
  6. #include <array>
  7. #include <string>
  8. #include <fstream>
  9. namespace al {
  10. // Windows' std::ifstream fails with non-ANSI paths since the standard only
  11. // specifies names using const char* (or std::string). MSVC has a non-standard
  12. // extension using const wchar_t* (or std::wstring?) to handle Unicode paths,
  13. // but not all Windows compilers support it. So we have to make our own istream
  14. // that accepts UTF-8 paths and forwards to Unicode-aware I/O functions.
  15. class filebuf final : public std::streambuf {
  16. std::array<char_type,4096> mBuffer;
  17. HANDLE mFile{INVALID_HANDLE_VALUE};
  18. int_type underflow() override;
  19. pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override;
  20. pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override;
  21. public:
  22. filebuf() = default;
  23. ~filebuf() override;
  24. bool open(const wchar_t *filename, std::ios_base::openmode mode);
  25. bool open(const char *filename, std::ios_base::openmode mode);
  26. bool is_open() const noexcept { return mFile != INVALID_HANDLE_VALUE; }
  27. void close();
  28. };
  29. // Inherit from std::istream to use our custom streambuf
  30. class ifstream final : public std::istream {
  31. filebuf mStreamBuf;
  32. public:
  33. ifstream(const wchar_t *filename, std::ios_base::openmode mode = std::ios_base::in);
  34. ifstream(const std::wstring &filename, std::ios_base::openmode mode = std::ios_base::in)
  35. : ifstream(filename.c_str(), mode) { }
  36. ifstream(const char *filename, std::ios_base::openmode mode = std::ios_base::in);
  37. ifstream(const std::string &filename, std::ios_base::openmode mode = std::ios_base::in)
  38. : ifstream(filename.c_str(), mode) { }
  39. ~ifstream() override;
  40. bool is_open() const noexcept { return mStreamBuf.is_open(); }
  41. void close() { mStreamBuf.close(); }
  42. };
  43. } // namespace al
  44. #else /* _WIN32 */
  45. #include <fstream>
  46. namespace al {
  47. using filebuf = std::filebuf;
  48. using ifstream = std::ifstream;
  49. } // namespace al
  50. #endif /* _WIN32 */
  51. #endif /* AL_FSTREAM_H */