正在从std::fstream检索文件描述符

Retrieving file descriptor from a std::fstream

本文关键字:文件 描述 检索 fstream std      更新时间:2023-10-16

可能重复:
从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++中都不支持公开文件描述符。