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

标签 c++ utf-8 stream fopen

我能否使用 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 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 类)。

关于c++ - 将 C 文件句柄分配给 C++ 文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46417264/

相关文章:

c++ - 如何使用 Matlab mex 输出二维整数数组?

mysql替换重音字符

perl - Perl 中元音变音 "ü"的正确存储值是多少?

java - InputStream 读取源中不存在的额外字节

javascript - Node.js:使用顺序+异步输入/输出进行并行处理

c# - 如何使用WPF MediaKit播放YouTube视频?

c++ - 插件 DLL 引用的 DLL 的搜索路径

c++ - for循环中的热点

c++ - Printf 不弹出

linux - 获取对话框以显示 utf-8