
freopen
freopen是被包含于C标準库头档案<stdio.h>中的一个函式,用于重定向输入输出流。该函式可以在不改变代码原貌的情况下改变输入输出环境,但使用时应当保证流是可靠的。
基本介绍
- 外文名:freopen
- 头档案:stdio.h
- 类别:C标準库函式
- 功能::把一个存在档案流指定到另一档案
函式简介
函式名:freopen
函式,以指定模式重新指定到另一个档案。模式用于指定新档案的访问方式。
头档案:stdio.h
C89函式声明:
FILE *freopen( const char *filename, const char *mode, FILE *stream );
C99函式声明:
FILE *freopen(const char * restrict filename, const char * restrict mode, FILE * restrict stream);
形参说明:
filename:需要重定向到的档案名称或档案路径。
mode:代表档案访问许可权的字元串。例如,"r"表示“唯读访问”、"w"表示“只写访问”、"a"表示“追加写入”。
stream:需要被重定向的档案流。
返回值:如果成功,则返回该指向该输出流的档案指针,否则返回为NULL。
程式例
举例1
#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.\n"); /*close the standard output stream*/ fclose(stdout); return 0;}
举例2
如果上面的例子您没看懂这个函式的用法的话,请看这个例子。这个例子实现了从stdout到一个文本档案的重定向。即,把输出到萤幕的文本输出到一个文本档案中。
#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;}
编译运行一下,你会发现,十个数输出到了D糟根目录下文本档案output.txt中。
举例3
从档案in.txt中读入数据,计算加和输出到out.txt中
#include<stdio.h>int main(){ int a, b; freopen("in.txt","r",stdin); /* 如果in.txt不在连线后的exe的目录,需要指定路径如D:\in.txt */ freopen("out.txt","w",stdout); /*同上*/ while (scanf("%d%d", &a, &b) != EOF) printf("%d\n",a+b); fclose(stdin); fclose(stdout); return 0;}
恢复档案流
当标準输出stdout被重定向到指定档案后,如何把它重定向回原来“默认”的输出设备(即显示器)呢?
C标準库的回覆是:不支持。没有任何方法可以恢复原来的输出流。
那是否存在依赖具体平台的实现呢?存在。
在作业系统中,命令行控制台(即键盘或者显示器)被视为一个档案,既然是档案,那幺就有“档案名称”。由于历史原因,命令行控制台档案在DOS作业系统和Windows作业系统中的档案名称为"CON",在其它的作业系统(例如Unix、Linux、Mac OS X、Android等等)中的档案名称为"/dev/tty"。
因此,在Windows中可以使用
freopen( "CON", "w", stdout );
其它作业系统中使用:
freopen( "/dev/tty", "w", stdout );
Windows代码举例
#include<stdio.h>#include<stdlib.h>int main(){ FILE *stream; 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"); return 0;}
Linux代码举例
#include <stdio.h>#include <stdlib.h>int main(void){ FILE *stream; if ((stream = freopen("file.txt", "w", stdout)) == NULL) exit(-1); printf("this is stdout output\n"); stream = freopen("/dev/tty","w",stdout); /*stdout是向程式的末尾的控制台重定向*/ printf("And now back to the console once again\n"); return 0;}
警告:在使用上述方法在输入输出流间进行反覆的重定向时,极有可能导致流指针得到不被期待的结果,使输入输出发生异常,所以如果需要在档案的输入输出和标準输入输出流之间进行切换,建议使用fopen或者是C++标準的ifstream及ofstream。