UC编程:输入输出重定向(标准IO)

[c] #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; char szBuf[100]; /* 将屏幕标准输出的内容重定向到文件 */ if((fp = freopen("./1", "w", stderr)) == NULL) { perror("freopen"); return EXIT_FAILURE; } /* stderr已经输出重定向,所有的错误输出都将写入文件./1中 */ fputs("I like linux.", stderr); /* 关闭文件 */ fclose(fp); /* 将标准输入由键盘输入更改为从文件./1中读入*/ if((fp = freopen("./1" ,"r", stdin)) == NULL) { perror("freopen"); return EXIT_FAILURE; } memset(szBuf, 0, sizeof(szBuf)); /* stdin已经输入重定向, 所有内容都将写入文件./1中 */ fgets(szBuf, sizeof(szBuf), stdin); printf("szBuf = [%s]\n", szBuf); /* 关闭文件 */ fclose(fp); return 0; } [/c] 上面的程序摘自《精通Unix下C语言编程与项目实践》 运行结果: [code] [sincerefly@localhost UC]$ ./a.out szBuf = [I like linux.] [sincerefly@localhost UC]$ [/code] 也就是说,通过使用标准库中的freopen函数实现了输入输出的重定向 再来多看看两个例子,来自freopen函数的百度百科 举例1: [c] #include <stdio.h> int main() { /* redirect standard output to a file */ if (freopen("D:\\OUTPUT.txt", "w", stdout)==NULL) fprintf(stderr, "error redirecting stdout\n"); /* this output will go to a file */ printf("This will go into a file."); /* close the standard output stream */ fclose(stdout); return 0; } [/c] 举例2: [c] #include <stdio.h> int main() { int i; if (freopen("./OUTPUT.txt", "w", stdout)==NULL) fprintf(stderr, "error redirecting\stdout\n"); for(i=0;i<10;i++) printf("%3d",i); printf("\n"); fclose(stdout); return 0; } [/c] 从文件in.txt中读入数据,计算加和输出到out.txt中 举例3: [c] #include <stdio.h> int main() { freopen("in.txt","r",stdin); /*如果in.txt不在连接后的exe的目录,需要指定路径如./in.txt*/ freopen("out.txt","w",stdout);/*同上*/ int a,b; while(scanf("%d%d",&a,&b)!=EOF) printf("%d\n",a+b); fclose(stdin); fclose(stdout); return 0; } [/c] 若要返回到显示默认 stdout) 的 stdout,使用下面的调用: freopen( "CON", "w", stdout ); //输出到控制台"CON" 检查 freopen() 以确保重定向实际发生的返回值。 下面是短程序演示了 stdout 时重定向 举例4: [c] /*Compile options needed: none*/ #include <stdio.h> #include <stdlib.h> void main(void) { FILE *stream ; //将内容写到file.txt, "W"是写 ("r"是读) if((stream = freopen("file.txt", "w", stdout)) == NULL) exit(-1); printf("this is stdout output\n"); stream = freopen("CON", "w", stdout);/*stdout 是向程序的末尾的控制台重定向*/ printf("And now back to the console once again\n"); } [/c]

posted on 2014-02-20 22:00  卖火柴的小东东  阅读(315)  评论(0编辑  收藏  举报

导航