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》

更多相关文章

  1. c语言fopen打开文件失败的原因是什么?
  2. c语言根号函数是什么
  3. C语言中在main函数中定义的变量是全局变量么
  4. c语言fun函数有什么例题?
  5. C++中字符串比较函数strcmp怎么用?
  6. C程序总是以main函数作为程序执行的起始行,对么
  7. c语言中pow函数的用法是什么?
  8. c语言中将一个字符串转换到整型数据类型的函数是什么?
  9. c语言fopen函数的用法

随机推荐

  1. Android 自己动手写ListView学习其原理 2
  2. Android(安卓)TV Input Framework(TIF)--
  3. android无framework Java应用开发
  4. Android(安卓)中日期和秒数的转换
  5. Android菜单详解(四)——使用上下文菜单Con
  6. android技术篇(一)解锁bootloader
  7. Android中MediaMuxer跟MediaCodec用例
  8. Android自动化测试之如何安装Android虚拟
  9. Android与JS互调的简单使用
  10. android开启线程的误区