从 std::fstream 获取 FILE*

2023-01-22C/C++开发问题
1

本文介绍了从 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*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6