C-重定向
说实话,第一次接触重定向这一个概念,感觉是那么的神奇简洁不可思议……………………
freopen() 本来应该是打开的是文件指针,但是分配了指针,使她(亲切)指向了标准输入、输出、错误流。
用 法: FILE *freopen(const char *filename,const char *type, FILE *stream);
头文件:stdio.h
值得注意的是,如果stream已经打开,应该首先将其关闭。
来自百度百科的实例:
#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;}于是乎,就将0--9写入了文件。
例三:
从一个文件中读取数据计算之后,将数据写入另外一个文件
#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;}这样就从in.txt读取数据,然后处理,最后写入out.txt文件。在这过程中,不需要你插手。#_# 越来越喜欢她(爱)了
若要返回到显示默认状态,使用下面的调用:
freopen( "CON", "w", stdout ); //输出到控制台"CON"
检查 freopen() 以确保重定向实际发生的返回值。
/*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");}警告:在使用上诉方法在输入输出流间进行反复的重定向时,极有可能导致流指针得到不被期待的结果,是输入输出发生异常,所以如果需要在文件的输入输出和标准输入输出流之间进行切换建议使用fopen或者是c++标准的ifstream及ofstream。

浙公网安备 33010602011771号