C语言的文件操作 freopen

今天做USACO  用到了文件的操作。 之前做USACO只是格式化的些 写  freopen("xxx.in","r",stdin)  和"freopen("xxx.out","w",stdout)"  

百度百科上是这么介绍的:

    函数名: freopen

  功 能: 替换一个流,或者说重新分配文件指针,实现重定向。如果stream流已经打开,则先关闭该流。如果该流已经定向,则freopen将会清除该定向。此函数一般用于将一个指定的文件打开一个预定义的流:标准输入、标准输出或者标准出错。
  用 法: FILE *freopen(const char *filename,const char *type, FILE *stream);
    头文件:stdio.h

  

例1:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    if(freopen("file.txt","w",stdout)==NULL)
        fprintf(stderr,"error\n");
    printf("This is in the file\n");      //这句话会在file.txt中显示。
    fclose(stdout);               //使用fclose()函数就可以把缓冲区内最后剩余的数据输出到磁盘文件中,并释放文件指针和有关的缓冲区。
    return 0;
}

  

例2:

//首先在同路径下创建一个in.txt文本文档写入若干数字
#include <stdio.h>
#include <stdlib.h>

int main()
{
    freopen("in.txt","r",stdin);     //从in.txt 中读入数据
    freopen("out.txt","w",stdout);  // 将最后数据写入out.txt中
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF)     //数据是从in.txt中输入的
        printf("%d\n",a+b);             //写入out.txt中
    fclose(stdin);
    fclose(stdout);
    return 0;
}

 freopen("CON","w",stdout)  表示在控制台窗口上写入数据;

例3:

  

#include <stdio.h>
#include <stdlib.h>

int main()
{
   // FILE *stream;
    freopen("file1.txt","w",stdout);
    printf("this is in file1.txt");      // 这句话在file1.txt中显示
    freopen("CON","w",stdout);
    printf("And this is in command.\n");    //这句话在控制台上显示
    return 0;
}

  例5:  关于fread   可以通过下面的程序,一看就知道什么意思了

  

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     FILE *stream
 7     char s[102400]="";
 8     if((stream=freopen("file.txt","r",stdin))==null)
 9         exit(-1);
10     fread(s,1,1024,stdin);    // 读取file.txt中1到1024位,放入s中 ,我是这么理解的
11     printf("%s\n",s);
12     return 0;
13 }
原文地址:https://www.cnblogs.com/shenshuyang/p/2493472.html