輸入輸出重定向


想象一下,當我們寫了個程序,開始是在命令行下運行的程序,后來用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;

好,就這些了,希望對你有幫助。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM