int
main() {
string file_name = "/home/zhihui/Videos/test";
ofstream local(file_name,std::ios::binary);
local << "test file." << endl; //输出到文件
local << "try somthing bad." << endl; //输出到文件
auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer
std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
// buffer of 'local' object
// now std::cout work with 'local' buffer
// you don't see this message
std::cout << "some message"; //本来输出到屏幕的标准输出流被关联到文件输出流,会显示到文件里
// go back to old buffer
std::cout.rdbuf(cout_buff); //将标准输出流恢复
// you will see this message
std::cout << "back to default buffer\n";
auto fstream_buf = local.rdbuf();
local.basic_ios<char>::rdbuf(std::cout.rdbuf()); //文件输出流被关联到标准输出流
local << "try somthing new." << endl;//这时直接输出到屏幕而不是文件
return 0;
}
文件中输出的信息
test file.
try somthing bad.
some message
屏幕输出的信息
back to default buffer
try somthing new.