freopen重定向

函数名: freopen
  功 能: 替换一个流
  用 法: FILE *freopen(char *filename, char *type, FILE *stream);
  程序例:
  #include <stdio.h>
  int main(void)
  {
  /* redirect standard output to a file */
  if (freopen("OUTPUT.FIL", "w", stdout)
  == NULL)
  fprintf(stderr, "error redirectingstdout\n");
  /* this output will go to a file */
  printf("This will go into a file.");
  /* close the standard output stream */
  fclose(stdout);
  return 0;
  }

===========================================================
上面不懂, 可以向下看, 没关系. 实践+理论 , 会慢慢在这详解.., 慢慢看.
下面重点:

在这再说一下. 不然很难理解, 我都没想到. 一直困惑不清啊....stdin stdout stderr.
现在懂了.

牢记:   目前主要的缓存特征是:stdin和stdout是行缓存;而stderr是无缓存的。
本文介绍如何将 stdout 时重定向到文件从某个 C 的程序,然后还原原始的 stdout 同一程序的某个更高位置。 C 函数通常用于重定向 stdout 或 stdin 是 freopen()。 要将 stdout 时重定向到文件名为 FILE.TXT 中,使用下面的调用: 
freopen( "file.txt", "w", stdout ); //把内容写到这个文件"file.txt"
此语句使所有的后续输出,通常定向到转到文件 FILE.TXT stdout,向。

若要返回到显示默认 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\n"); 
   stream = freopen("CON", "w", stdout);stdout 是向程序的末尾的控制台重定向 
   printf("And now back to the console once again\n");
}

"CON" 是指控制台 就想DOS窗口.
==========================================
运行代码: 
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
   FILE *stream ;
    char s[102400]="";
   if((stream = freopen("file.txt", "r", stdin)) == NULL) //从文件读数据 (放到stdin , 其实stdin 也有自己的缓冲区.就向buf) 
      exit(-1);

    fread(s, 1, 1024, stdin); //所以从标准输入里读出数据. 因为要注意stdin也是有自己的一块缓冲区.

   printf("%s\n", s); //在这里打印读出来的数据.

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值