freopen重定向

来源:互联网 发布:xampp mac配置环境 编辑:程序博客网 时间:2024/05/01 22:52
函数名: 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 0
原创粉丝点击