微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

freopen函数的用法详解

freopen 函数说明

函数名: freopen 
功  能: 实现数据重定向文件中 
用  法: FILE *freopen(const char *filename, const char *mode, FILE *stream); 
返回值: 成功,则返回文件指针;失败,返回NULL(可以不使用它的返回值) 7 
#include <stdio.h> 

int main(void) 
{ 
   /* redirect standard output to a file */ 
   if (freopen(OUTPUT.FIL, 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; 
}

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

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

freopen函数在调试中非常有用:

freopen(debug\\in.txt,r,stdin)的作用就是把标准输入流stdin重定向到debug\\in.txt文件中,这样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从in.txt文件获取输入。

只要把输入数据事先粘贴到in.txt,调试时就方便多了。

类似的,freopen(debug\\out.txt,w,stdout)的作用就是把stdout重定向到debug\\out.txt文件中,这样输出结果需要打开out.txt文件查看。

需要说明的是:

1. 在freopen(debug\\in.txt,r,stdin)中,将输入文件in.txt放在文件夹debug中,文件夹debug是在VC中建立工程文件自动生成的调试文件夹。如果改成freopen(in.txt,r,stdin),则in.txt文件将放在所建立的工程文件夹下。in.txt文件也可以放在其他的文件夹下,所在路径写正确即可。

2. 可以不使用输出重定向,仍然在控制台查看输出。 3. 程序调试成功后,提交到oj时不要忘记把与重定向有关的语句删除

推荐教程: 《c

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐