Getting a FILE* from a std::fstream(从 std::fstream 获取 FILE*)
问题描述
是否有(跨平台)方法可以从 C++ std::fstream 获取 C FILE* 句柄?
Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?
我问的原因是因为我的 C++ 库接受 fstreams,并且在一个特定的函数中,我想使用一个接受 FILE* 的 C 库.
The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.
推荐答案
简短的回答是否定的.
原因是 std::fstream 不需要使用 FILE* 作为其实现的一部分.因此,即使您设法从 std::fstream 对象中提取文件描述符并手动构建 FILE 对象,您也会遇到其他问题,因为您现在将有两个缓冲对象写入同一个文件描述符.
The reason, is because the std::fstream is not required to use a FILE* as part of its implementation. So even if you manage to extract file descriptor from the std::fstream object and manually build a FILE object, then you will have other problems because you will now have two buffered objects writing to the same file descriptor.
真正的问题是为什么要将 std::fstream 对象转换为 FILE* 对象?
The real question is why do you want to convert the std::fstream object into a FILE*?
虽然我不推荐它,但你可以尝试查找 funopen().
不幸的是,这不是一个 POSIX API(它是一个 BSD 扩展)所以它的可移植性是有问题的.这也可能是为什么我找不到任何用这样的对象包装 std::stream 的原因.
Though I don't recommend it, you could try looking up funopen().
Unfortunately, this is not a POSIX API (it's a BSD extension) so its portability is in question. Which is also probably why I can't find anybody that has wrapped a std::stream with an object like this.
FILE *funopen(
const void *cookie,
int (*readfn )(void *, char *, int),
int (*writefn)(void *, const char *, int),
fpos_t (*seekfn) (void *, fpos_t, int),
int (*closefn)(void *)
);
这允许您构建一个 FILE 对象并指定一些将用于执行实际工作的函数.如果您编写了适当的函数,您可以让它们从实际打开文件的 std::fstream 对象中读取.
This allows you to build a FILE object and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from the std::fstream object that actually has the file open.
这篇关于从 std::fstream 获取 FILE*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 std::fstream 获取 FILE*
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
