根据 Éric Malenfant 给出的答案:
AFAIK,没有办法做到这一点
标准C++。取决于您的
平台,您的实施
标准库可能提供(作为
非标准扩展)fstream
构造函数获取文件描述符
作为输入。 (这种情况是
libstdc++、IIRC) 或 FILE*。
根据上述观察和我下面的研究,有两种变体的工作代码;一个用于 libstdc++,另一个用于 Microsoft Visual C++。
libstdc++ 库
有不标准的__gnu_cxx::stdio_filebuf http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.6/a00068.html继承的类模板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 传递给 istream 的构造函数(第 2 行):
#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;
}
微软视觉C++
以前有不标准的version http://msdn.microsoft.com/en-us/library/aa243822%28v=VS.60%29.aspxifstream 的构造函数采用 POSIX 文件描述符,但缺少这两个文件描述符current http://msdn.microsoft.com/en-us/library/zek0beca%28v=VS.100%29.aspx文档和代码。 ifstream 的构造函数还有另一个非标准版本,它采用 FILE*
explicit basic_ifstream(_Filet *_File)
: _Mybase(&_Filebuffer),
_Filebuffer(_File)
{ // construct with specified C stream
}
并且它没有记录(我什至找不到任何旧文档)。我们调用它(第 1 行),参数是调用的结果_fdopen http://msdn.microsoft.com/en-us/library/dye30d82%28v=VS.100%29.aspx从 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;
}