输入输出重定向

想象一下,当我们写了个程序,开始是在命令行下运行的程序,后来用MFC之类的改写为窗体程序,原先用printf输出的trace都不可见了,但是我们又需要(输出到文件分析),怎么办?
1、开始写的时候你定义一个MyTrace的宏;
2、你可以把printf换成fprintf;
3、使用输出重定向。

第一种情况很方便,可程序已经写出来了,显然不大可能;
第二种情况可以是可以,但劳动量比较大;
第三种我觉得可以。

还记得不,在windows终端输入 "dir > 1.txt",或在linux终端输入"ls > 1.txt",即可实现把当前目录的文件列表导出到"1.txt"中。这里就用到了输出重定向,很方便吧,我们也可以仿照这个去做。

这里只是提供一个思路,下面有几段IO重定向的示例代码,有C的,python的,还有perl的(年终总结,三种语言都总结了,哈哈),仅供参考。

基于c的示例代码:

 1 /*
2 File : redirect.c
3 Author : Mike
4 E-Mail : Mike_Zhang@live.com
5 */
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 void test_stdin()
10 {
11 char buf[128];
12 freopen("1.txt", "r", stdin); //redirect stdin
13 scanf("%s",buf);
14 printf("%s\n",buf);
15 freopen("CON", "r", stdin); //recover(Windows)
16 //freopen("/dev/console", "r", stdin); //recover(Linux)
17 //freopen("/dev/pts/0", "r", stdin); //recover stdin(Linux : my putty client)
18 scanf("%s",buf);
19 printf("%s\n",buf);
20 }
21
22 void test_stdout()
23 {
24 freopen("1.txt", "w", stdout); //redirect stdout
25 printf("test");
26 freopen("CON", "w", stdout); //recover stdout(Windows)
27 //freopen("/dev/console", "w", stdout); //recover stdout(Linux)
28 //freopen("/dev/pts/0", "w", stdout); //recover stdout(Linux : my putty client)
29 printf("OK\n");
30 }
31
32 int main()
33 {
34 printf("Test stdout : \n");
35 test_stdout();
36 printf("Test stdin : \n");
37 test_stdin();
38 return 0;
39 }

基于python的示例代码:

 1 #! /usr/bin/python
2 import sys
3 '''
4 File : redirect.py
5 Author : Mike
6 E-Mail : Mike_Zhang@live.com
7 '''
8 print "Test stdout : "
9 #redirect stdout
10 tmp = sys.stdout
11 fp = open("1.txt","w")
12 sys.stdout = fp
13 print 'Just a test'
14 sys.stdout = tmp #recover stdout
15 print 'test2'
16 fp.close()
17
18 print "Test stdin : "
19 #redirect stdin
20 tmp = sys.stdin
21 fp = open("1.txt","r")
22 sys.stdin = fp
23 strTest = raw_input()
24 print strTest
25 sys.stdin = tmp # recover stdin
26 strTest = raw_input()
27 print strTest
28 fp.close()

基于perl的示例代码:

 1 #! /usr/bin/perl
2 =cut
3 File : redirect.pl
4 Author : Mike
5 E-Mail : Mike_Zhang@live.com
6 =cut
7
8 #redirect STDOUT
9 print "Test stdout : \n";
10 open LOG,"> 2.txt";
11 select LOG;
12 print "just a test\n";
13 #recover STDOUT
14 select STDOUT;
15 print "just a test2\n";
16 close LOG;
17
18 #redirect STDIN
19 print "Test stdin : \n";
20 open LOG2,"< 2.txt";
21 $line = <LOG2>;
22 print $line;
23 close LOG2;
24 $line = <STDIN>;
25 print $line;

好,就这些了,希望对你有帮助。

posted on 2012-01-19 13:38  Mike_Zhang  阅读(5547)  评论(1编辑  收藏  举报