说实话,第一次接触重定向这一个概念,感觉是那么的神奇简洁不可思议……………………
freopen() 本来应该是打开的是文件指针,但是分配了指针,使她(亲切)指向了标准输入、输出、错误流。
#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;}#include <stdio.h>int main(){ int i; if (freopen("D:\\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;}#include <stdio.h>int main(){ freopen("in.txt","r",stdin); /*如果in.txt不在连接后的exe的目录,需要指定路径如D:\\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;}/*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");}原文:http://www.cnblogs.com/plxx/p/3574056.html