请输入您要查询的百科知识:

 

词条 freopen
释义

函数简介

函数名: freopen

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

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

头文件:stdio.h

程序例

举例1:

#include <stdio.h>

int main()

{

/* redirect standard output to a file */

if (freopen("D:OUTPUT.txt", "w", stdout)==NULL)

fprintf(stderr, "error redirecting\\stdout\");

/* 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 <stdio.h>

int main()

{

int i;

if (freopen("D:OUTPUT.txt", "w", stdout)==NULL)

fprintf(stderr, "error redirecting\\stdout\");

for(i=0;i<10;i++)

printf("%3d",i);

printf("\");

fclose(stdout);

return 0;

}

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

举例3:

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

#include <iostream.h>

#include <cstdio.h>

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\",a+b);

fclose(stdin);

fclose(stdout);

return 0;

}

举例4:

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

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

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

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

运行代码

// Compile options needed: none

#include <stdio.h>

#include <stdlib.h>

void main(void)

{

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

if((stream = freopen("file.txt", "w", stdout)) == NULL)

exit(-1); printf("this is stdout output\");

stream = freopen("CON", "w", stdout);stdout 是向程序的末尾的控制台重定向

printf("And now back to the console once again\");

}

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/2/12 14:10:21