C++ 从 std::fstream 检索文件描述符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11558447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving file descriptor from a std::fstream
提问by Abruzzo Forte e Gentile
Possible Duplicate:
Getting a FILE* from a std::fstream
可能的重复:
从 std::fstream 获取 FILE*
I am working on Linux and file descriptors are the main model in this OS.
我在 Linux 上工作,文件描述符是这个操作系统的主要模型。
I was wondering whether is there any library or any way to retrieve the native Linux file descriptor starting from a C++ std::fstream
.
我想知道是否有任何库或任何方法可以从 C++ 开始检索本机 Linux 文件描述符std::fstream
。
I thought about boost::iostream
since there is a class called file_descriptor
but I understood that its purpose is different from the one I want to achieve.
我想过boost::iostream
因为有一个类叫,file_descriptor
但我明白它的目的和我想要实现的目的不同。
Do you know some way to do that?
你知道有什么方法可以做到吗?
采纳答案by Maxim Egorushkin
You can go the other way: implement your own stream buffer that wraps a file descriptor and then use it with iostream
instead of fstream
. Using Boost.Iostreamscan make the task easier.
您可以采用另一种方式:实现您自己的流缓冲区来包装文件描述符,然后使用它iostream
代替fstream
. 使用Boost.Iostreams可以使任务更容易。
Non-portable gcc solution is:
非便携式 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.
}
回答by Hampus Nilsson
There is no (standard) way to extract the file number from an std::fstream since the standard library does not mandate how file streams will be implemented.
没有(标准)方法可以从 std::fstream 中提取文件编号,因为标准库不强制要求如何实现文件流。
Rather, you need to use the C file API if you want to do this (using FILE*
).
相反,如果要执行此操作(使用FILE*
),则需要使用 C 文件 API 。
回答by Some programmer dude
There is no official way to get the private file handle of a file stream (or actualy a std::basic_filebuf
), just because it should be portable and discourage use of platform-specific functions.
没有官方的方法来获取文件流(或实际上 a std::basic_filebuf
)的私有文件句柄,只是因为它应该是可移植的并且不鼓励使用特定于平台的功能。
However, you can do ugly hack like inheriting std::basic_filebuf
and from that try to pry out the file handle. It's not something I recommend though as it will probably break on different versions of the C++ library.
但是,您可以进行诸如继承之类的丑陋黑客攻击,std::basic_filebuf
并从中尝试撬出文件句柄。这不是我推荐的东西,因为它可能会在不同版本的 C++ 库上中断。
回答by Artyom
There is no support of exposing file descriptor neither in standard C++ nor in libstdc++
.
标准 C++ 和libstdc++
.