alfstream.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. };
  28. // Inherit from std::istream to use our custom streambuf
  29. class ifstream final : public std::istream {
  30. filebuf mStreamBuf;
  31. public:
  32. ifstream(const wchar_t *filename, std::ios_base::openmode mode = std::ios_base::in);
  33. ifstream(const std::wstring &filename, std::ios_base::openmode mode = std::ios_base::in)
  34. : ifstream(filename.c_str(), mode) { }
  35. ifstream(const char *filename, std::ios_base::openmode mode = std::ios_base::in);
  36. ifstream(const std::string &filename, std::ios_base::openmode mode = std::ios_base::in)
  37. : ifstream(filename.c_str(), mode) { }
  38. ~ifstream() override;
  39. bool is_open() const noexcept { return mStreamBuf.is_open(); }
  40. };
  41. } // namespace al
  42. #else /* _WIN32 */
  43. #include <fstream>
  44. namespace al {
  45. using filebuf = std::filebuf;
  46. using ifstream = std::ifstream;
  47. } // namespace al
  48. #endif /* _WIN32 */
  49. #endif /* AL_FSTREAM_H */