可可西

cout重定向到文件

cout默认是与监视器(屏幕)相连,cout出来的内容会输出到屏幕上,通常是会在命令行窗口之中。但有时,我们希望将cout出来的具体日志、错误信息写到某个文件之中,而屏幕上仅仅显示出当前进行的任务,以及程序运行状态等信息。我们可以使用下面重定向的方式来实现:

 

1 #include "stdafx.h"
2 #include <iostream>
3 #include <fstream>
4
5  int main(int argc, char* argv[])
6 {
7 using namespace std;
8
9 cout << "Hello, Let's begin a test of cout to file." << endl;
10 // 保存cout流缓冲区指针
11   streambuf* coutBuf = cout.rdbuf();
12
13 ofstream of("out.txt");
14 // 获取文件out.txt流缓冲区指针
15   streambuf* fileBuf = of.rdbuf();
16
17 // 设置cout流缓冲区指针为out.txt的流缓冲区指针
18   cout.rdbuf(fileBuf);
19 cout << "Name " << "Chen" << endl;
20 cout << "Sex " << "Female" << endl;
21 cout << "E-mail"<< "Chen@qq.com" << endl;
22
23 of.flush();
24 of.close();
25
26 // 恢复cout原来的流缓冲区指针
27   cout.rdbuf(coutBuf);
28 cout << "Write Personal Information over..." << endl;
29
30 system("PAUSE");
31 return 0;
32 }

 

运行后的结果:

写入到“out.txt”中的内容:

 

 

posted on 2010-07-18 15:32  可可西  阅读(6099)  评论(0编辑  收藏  举报

导航