調べてみたら多少手間だったので忘備録。
C++の初期のstreamにはstdiostreamというものがあったらしい。いまだに使える処理系もあるようだが、使えない処理系もある。現在は標準的な方法がないようだ。
gcc(libstdc++ 3.1 and later)の場合(Chapter 38. Input and Output):
#include <cstdio>
#include <ext/stdio_filebuf.h>
FILE *fp = fopen(”somefile.txt”, “rt”);
__gnu_cxx::stdio_filebuf<char> filebuf_from_fp(fp, std::ios_base::in);
std::istream istream_from_fp(&filebuf_from_fp);
Microsoft Visual C++の場合(ドキュメントにはないが、basic_filebufをFILE*から構築できる; VC6.0と.NET 2003で確認):
#include <cstdio>
#include <fstream>
FILE *fp = fopen(”somefile.txt”, “rt”);
std::filebuf filebuf_from_fp(fp);
std::istream istream_from_fp(&filebuf_from_fp);
あとは普通のstreamとして使用できる。
istream_from_fp.unsetf(std::ios_base::skipws);
std::copy(std::istream_iterator(istream_from_fp), std::istream_iterator(), std::ostream_iterator(std::cout));
以上。