freopen是被包含于C标准库头文件<stdio.h>中的一个函数,用于重定向输入输出流。该函数可以在不改变代码原貌的情况下改变输入输出环境,但使用时应当保证流是可靠的。
函数名: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
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <stdio.h>
int
main(
void
)
{
/* 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
从文件in.txt中读入数据,计算加和输出到out.txt中
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <stdio.h>
int
main(
void
)
{
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代码举例
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#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
(
"CON"
,
"w"
,stdout);
/*stdout是向程序的末尾的控制台重定向*/
printf
(
"And now back to the console once again\n"
);
return
0;
}
|