freopen是被包含于C标准库头文件<stdio.h>中的一个函数,用于重定向输入输出流。该函数可以在不改变代码原貌的情况下改变输入输出环境。
FILE *freopen(const char * restrict filename, const char * restrict mode, FILE * restrict stream);
#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;
}
再看一个例子,在D盘的目录下,新建立一个文件,把一串数字写入到文件中去:
#include <stdio.h>
int main(void)
{
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中
#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;
}
从文件in.txt中读入数据,计算相邻两个数的加和输出到out.txt中
由于这里面用到了scanf这个函数,这里有必要说一下:
scanf("%d %d",&a,&b);
原文:http://www.cnblogs.com/stemon/p/4595624.html