函数名:freopen
声明:FILE *freopen( const char *path, const char *mode, FILE *stream );
所在文件: stdio.h
参数说明:
path: 文件名,用于存储输入输出的自定义文件名。
mode: 文件打开的模式。
DESCRIPTION
The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.
The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
r Open text file for reading. The stream is positioned at the beginning of the file.
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning
of the file, but output is always appended to the end of the file.
stream: 一个文件,通常使用标准流文件,stdin, stdout, stderr。
返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般可以不使用它的返回值)
功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。
标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。
实例:
#include <stdio.h>
int main() {
int a,b;
freopen("debug\\in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
freopen("debug\\out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
while(scanf("%d %d",&a,&b)!=EOF)
printf("%d\n",a+b);
fclose(stdin);//关闭文件
fclose(stdout);//关闭文件
freopen("dev/console", "w", stdout); //重新打开输出到屏幕,linux平台
freopen("dev/console", "r", stdin); //重新定位到标准输入,linux平台
return 0;
}
python: 对print的输出重定向:import sys
temp = sys.stdout
file = open('f.txt','w')
sys.stdout = file
print (1,2,3)
sys.stdout.close()
sys.stdout = temp
print (1,2,3)