freopen是被包含于C标准库头文件<stdio.h>中的一个函数,用于重定向输入输出流。该函数可以在不改变代码原貌的情况下改变输入输出环境,但使用时应当保证流是可靠的。
举例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
|
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;
}
|
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;
}
|
361




被折叠的 条评论
为什么被折叠?



