将 C 文件句柄分配给 C++ 文件流

Assigning a C file handle to C++ file stream

我可以用 C 函数打开文件 (fopen) 并将该句柄分配给 C++ 文件流 (fstream...)吗?

提问原因:我想在 windows 上处理 UTF8,但是 fstream class 只有一个 const char* ctor/open 方法。所以我需要使用 C API 打开它,然后让一个流对象使用它。

甚至可以使用 boost 流库,因为它通常允许指定您自己的 sinks/sources 但我不知道从哪里开始。

说明:我想打开一个路径为 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 derived class that handles I/O using FILE*, and then assign an instance of that class to a standard std::istream object. See the implementation of std::basic_filebuf 来帮助你,或者 GNU 的 stdio_filebuf class.

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 a const wchar_t* does help, but MinGW does not provide these overloads. So I'd need to use wfopen on windows instead.

Windows 上的大多数 Unicode API 不支持 UTF-8,仅支持 UTF-16。因此 wchar_t 在 Visual C++ 和其他兼容编译器中重载。 Mingw 根本不支持这些扩展。不过,有 3rd 方解决方案。例如 Pathie(参见 Pathie::ifstreamPathie::ofstream class 等)。