随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

输入输出重定向

想象一下,当我们写了个程序,开始是在命令行下运行的程序,后来用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   Mike_Zhang  阅读(5552)  评论(1编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年1月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
5 6 7 8 9 10 11

点击右上角即可分享
微信分享提示