且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 std::fstream 获取 FILE*

更新时间:2023-02-05 17:09:54

简短的回答是否定的.

原因是 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.