freopen()函数

  freopen函数通过实现标准I/O重定向功能来访问文件,而fopen函数则通过文件I/O来访问文件。

  freopen函数在算法竞赛中常被使用。在算法竞赛中,参赛者的数据一般需要多次输入,而为避免重复输入,使用重定向。

 1 freopen 函数说明
 2 
 3 函数名: freopen 
 4 功  能: 实现数据重定向到文件中 
 5 用  法: FILE *freopen(const char *filename, const char *mode, FILE *stream); 
 6 返回值: 成功,则返回文件指针;失败,返回NULL(可以不使用它的返回值) 7 
 8 #include <stdio.h> 
 9 
10 int main(void) 
11 { 
12    /* redirect standard output to a file */ 
13    if (freopen("OUTPUT.FIL", "w", stdout) 
14        == NULL) {
15       fprintf(stderr, "error redirecting\ 
16               stdout\n"); 
17   }
18    /* this output will go to a file */ 
19    printf("This will go into a file."); 
20 
21    /* close the standard output stream */ 
22    fclose(stdout); 
23 
24    return 0; 
25 } 

  注意:算法竞赛中,filename不要使用绝对路径或者相对路径。

posted @ 2016-02-23 02:59  forget406  阅读(1750)  评论(0编辑  收藏  举报