標準入出力ストリーム(cin, cout等)の入出力先を一時的に変更するヘルパクラス。
std::ifstream("input.txt"); ioredirector rd0(std::cin, ifs); std::string s; while (std::getline(std::cin, s)) /* input.txtから1行読込 */; // coutへ出力... 標準出力へ // cerrへ出力... 標準エラー出力へ { std::ofstream ofs("log.txt"); ioredirector rd1(std::cout, ofs), rd2(std::cerr, ofs); // cout/cerrへ出力... "log.txt"へ } // cout/cerrの出力先は元通り
実装:
#include <ios> template <class E, class T = std::char_traits<E> > class basic_ioredirector { std::basic_ios<E, T>& src_; std::basic_streambuf<E, T> *oldbuf_; basic_ioredirector(const basic_ioredirector&); // =delete basic_ioredirector& operator=(const basic_ioredirector&); // =delete public: basic_ioredirector(std::basic_ios<E, T>& src, std::basic_ios<E, T>& dest) : src_(src), oldbuf_(src.rdbuf(dest.rdbuf())) {} ~basic_ioredirector() { src_.rdbuf(oldbuf_); } }; typedef basic_ioredirector<char> ioredirector; typedef basic_ioredirector<wchar_t> wioredirector;