我能否使用 C 函数 (fopen
) 打开文件并将该句柄分配给 C++ 文件流 (fstream
...)?
提问原因:我想在 Windows 上处理 UTF8,但是 fstream
类只有一个 const char*
ctor/open 方法。所以我需要使用 C API 打开它,然后让一个流对象使用它。
boost stream 库甚至可以实现,因为它通常允许指定您自己的接收器/源,但我不知道从哪里开始。
说明:我想打开一个路径为 UTF8 字符串的文件。因此文件打开方法必须支持 fstream
不支持的 UTF8 路径。接受 const wchar_t*
的 MSVC 扩展确实有帮助,但 MinGW 不提供这些重载。所以我需要在 Windows 上使用 wfopen
。
最佳答案
Can I open a file with C functions (
fopen
) and assign that handle to a C++ file stream (fstream
...)?
不直接,不。但是您可以编写(或查找)自定义 std::streambuf
使用 FILE*
处理 I/O 的派生类,然后将该类的实例分配给标准 std::istream
对象。查看 std::basic_filebuf
的实现来帮助你,或者 GNU 的 stdio_filebuf
类。
I want to open a file with a path given as an UTF8 string. So the file open method must support UTF8 paths which
fstream
does not. The MSVC extension accepting aconst wchar_t*
does help, but MinGW does not provide these overloads. So I'd need to usewfopen
on windows instead.
Windows 上的大多数 Unicode API 不支持 UTF-8,仅支持 UTF-16。因此 wchar_t
在 Visual C++ 和其他兼容编译器中重载。 Mingw 根本不支持这些扩展。不过,有 3rd 方解决方案。如Pathie (参见 Pathie::ifstream
和 Pathie::ofstream
类)。
关于c++ - 将 C 文件句柄分配给 C++ 文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46417264/