正在从std::fstream检索文件描述符
Retrieving file descriptor from a std::fstream
可能重复:
从std::fstream 获取文件*
我在Linux上工作,文件描述符是这个操作系统的主要模型。
我想知道是否有任何库或任何方法可以从C++std::fstream
开始检索本机Linux文件描述符。
我考虑过boost::iostream
,因为有一个类叫file_descriptor
,但我明白它的目的与我想要实现的目的不同。
你知道怎么做吗?
您可以走另一条路:实现自己的流缓冲区,该缓冲区封装文件描述符,然后将其与iostream
而不是fstream
一起使用。使用Boost.Iotstreams可以使任务变得更容易。
非便携式gcc解决方案是:
#include <ext/stdio_filebuf.h>
{
int fd = ...;
__gnu_cxx::stdio_filebuf<char> fd_file_buf{fd, std::ios_base::out | std::ios_base::binary};
std::ostream fd_stream{&fd_file_buf};
// Write into fd_stream.
// ...
// Flushes the stream and closes fd at scope exit.
}
没有(标准)方法从std::fstream中提取文件号,因为标准库没有规定如何实现文件流。
相反,如果您想这样做,您需要使用C文件API(使用FILE*
)。
没有官方的方法来获取文件流(或者实际上是std::basic_filebuf
)的私有文件句柄,只是因为它应该是可移植的,并且不鼓励使用特定于平台的功能。
然而,您可以进行丑陋的破解,比如继承std::basic_filebuf
,然后尝试从中撬出文件句柄。不过我并不推荐它,因为它可能会在不同版本的C++库中崩溃。
在标准C++和libstdc++
中都不支持公开文件描述符。
相关文章:
- 使用VerQueryValue检索应用程序的文件描述
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- I2C 文件描述符上的 I2C 总线可写/可读标志
- 许多文件描述符在调用sys_clone时
- AMQP-CPP >处理程序中的错误文件描述符
- 如何使用 WINAPI 和 C++ 提取可执行文件的文件描述?
- 正在等待在非阻塞文件描述符上长时间运行ioctl
- 有没有适用于Windows.lib文件的GNU二进制文件描述符(BFD)
- 如何强制文件描述符缓冲我的输出
- 如何从 boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 获取本机套接字文件描述器?
- 哪个更适合从C++写入敏感的日志文件,在文件描述符上写()或文件上的fprintf()?
- 将 select() 与非基于文件描述符的输入一起使用
- accept(..) 似乎正在修改我给它的文件描述符参数
- 使用 Select 多路复用未命名的管道和其他文件描述符
- 提升 ASIO 绑定:错误的文件描述符
- 使用文件描述符移动对象
- 无法从零MQ ZMQ_SERVER套接字中获取文件描述符
- read() 上的不同行为取决于写入不可写内存时表示文件、匿名管道或套接字的文件描述符
- 我可以在不使用 FIOCANCEL 的情况下关闭 VxWorks 中的文件描述符吗?
- 将 Boost Asio 与 ZeroMQ 集成,文件描述符错误?