文档库 最新最全的文档下载
当前位置:文档库 › C语言文件操作函数freopen

C语言文件操作函数freopen

C语言文件操作函数freopen
C语言文件操作函数freopen

freopen

目录

函数简介

程序例

函数简介

函数名: freopen

功能: 替换一个流,或者说重新分配文件指针,实现重定向。如果stream流已经打开,则先关闭该流。如果该流已经定向,则freopen将会清除该定向。此函数一般用于将一个指定的文件打开一个预定义的流:标准输入、标准输出或者标准出错。

用法: FILE *freopen(const char *filename,const char *type, FILE *stream);

头文件:stdio.h

返回值:如果成功则返回该指向该stream的指针,否则为NULL。

程序例

举例1:

#include

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.");

/* close the standard output stream */

fclose(stdout);

return 0;

}

举例2:

如果上面的例子您没看懂这个函数的用法的话,请看这个例子。这个例子实现了从stdout到一个文本文件的重定向。即,把输出到屏幕的文本输出到一个文本文件中。

#include

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;

}

在VC++6.0中运行一下,你会发现,十个数输出到了D盘下文本文件OUTPUT.txt中。举例3:

从文件in.txt中读入数据,计算加和输出到out.txt中

#include

#include

using namespace std;

int main()

{

freopen("in.txt","r",stdin);

freopen("out.txt","w",stdout);

int a,b;

while(scanf("%d%d",&a,&b)!=EOF)

printf("%d\n",a+b);

fclose(stdin);

fclose(stdout);

return 0;

}

举例4:[1]

若要返回到显示默认 stdout)的 stdout,使用下面的调用:

freopen( "CON", "w", stdout ); //输出到控制台"CON"

检查 freopen() 以确保重定向实际发生的返回值。

下面是短程序演示了 stdout 时重定向:

运行代码

// Compile options needed: none

#include

#include

void main(void)

{

FILE *stream ; //将内容写到file.txt, "W"是写 ("r"是读)

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");

}

相关文档