从 std::fstream 获取 FILE*

2021-12-09 00:00:00 file file-io c c++ fstream

是否有(跨平台)方法可以从 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.

相关文章