来自 Éric Malenfant 的回答:
AFAIK,没有办法做到这一点
标准 C++。取决于你的
平台,您的实施
标准库可以提供(作为
非标准扩展)一个 fstream
构造函数采用文件描述符
作为输入。 (这种情况适用于
libstdc++, IIRC) 或 FILE*。
基于上述观察和我在下面的研究,有两种变体的工作代码;一个用于 libstdc++,另一个用于 Microsoft Visual C++。
libstdc++
有一个非标准的__gnu_cxx::stdio_filebuf 类模板继承std::basic_streambuf 并具有以下构造函数
stdio_filebuf (int __fd, std::ios_base::openmode __mode, size_t __size=static_cast< size_t >(BUFSIZ))
带有描述此构造函数将文件流缓冲区与打开的 POSIX 文件描述符相关联。
我们通过 POSIX 句柄(第 1 行)创建它,然后我们将其作为 basic_streambuf(第 2 行)传递给 istream 的构造函数:
#include <ext/stdio_filebuf.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream ofs("test.txt");
ofs << "Writing to a basic_ofstream object..." << endl;
ofs.close();
int posix_handle = fileno(::fopen("test.txt", "r"));
__gnu_cxx::stdio_filebuf<char> filebuf(posix_handle, std::ios::in); // 1
istream is(&filebuf); // 2
string line;
getline(is, line);
cout << "line: " << line << std::endl;
return 0;
}
Microsoft Visual C++
ifstream 的构造函数中曾经有非标准的 version 采用 POSIX 文件描述符,但 current 文档和代码中都缺少它。 ifstream 的构造函数还有另一个非标准版本采用 FILE*
explicit basic_ifstream(_Filet *_File)
: _Mybase(&_Filebuffer),
_Filebuffer(_File)
{ // construct with specified C stream
}
而且它没有被记录(我什至找不到任何旧文档)。我们调用它(第 1 行),参数是调用 _fdopen 从 POSIX 文件句柄获取 C 流 FILE* 的结果。
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream ofs("test.txt");
ofs << "Writing to a basic_ofstream object..." << endl;
ofs.close();
int posix_handle = ::_fileno(::fopen("test.txt", "r"));
ifstream ifs(::_fdopen(posix_handle, "r")); // 1
string line;
getline(ifs, line);
ifs.close();
cout << "line: " << line << endl;
return 0;
}