使用文件来输入输出

   初学C语言用的方法:文件指针来操作。

首先我们需要定义文件指针,为了方便我们不妨定义2个,一个fp1用作输入文件指针,另一个fp2用作输出文件指针。

FILE *fp1,*fp2;

用fopen打开文件

fp1=fopen("test.txt","r"); //输入文件,以只读方式打开

fp2=fopen("testOut.text","w"); //输出文件,以写的方式打开i

fscanf(fp1,"%d",&x);      //从文件中输入

fprintf(fp2,"%d",x);      //输出到文件

fclose(fp1);  //关闭文件

fclose(fp2);

还有一种简单的方法。用freopen重定向

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

【参数说明】

filename: 要打开的文件名

mode: 文件打开的模式,和fopen中的模式(r/w)相同

stream: 文件指针,通常使用标准流文件(stdin/stdout/stderr)

【使用方法】

因为文件指针使用的是标准流文件,因此我们可以不定义文件指针。接下来我们使用freopen()函数以只读方式r(read)打开输入文件

freopen("test.in", "r", stdin);

然后使用freopen()函数以写入方式w(write)打开输出文件

freopen("test.out", "w", stdout);

最后只要使用fclose关闭输入文件和输出文件即可。

fclose(stdin);

fcolse(stdout);

fprintf:   int fprintf(FILE *stream,char *format [,argument])

#include <stdio.h>
int main()
{
   int i;
   if (freopen("test.txt", "w", stdout)==NULL)
   fprintf(stderr, "error redirecting\stdout\n");
   for(i=0;i<10;i++)
   printf("%3d",i);
   printf("\n");
   fclose(stdout);
   return 0;
}  //: int fprintf(FILE *stream,char *format [,argument])输到了文件中

若要返回到显示默认 stdout) 的 stdout,使用下面的调用:

 

 freopen( "CON", "w", stdout ); //输出到控制台"CON"

 

 检查 freopen() 以确保重定向实际发生的返回值。

 

 下面是短程序演示了 stdout 时重定向:

#include <stdio.h>
#include<stdlib.h>
int main()
{
    FILE *stream;
    if((stream=freopen("text.txt","w",stdout))==NULL)
    exit(-1);
    printf("this is a test");  // 输出到了文件中
    stream=freopen("CON","w",stdout); //
    printf("And now back to the console once again\n");//输出到了控制台上

  }
 
原文地址:https://www.cnblogs.com/youxin/p/2457312.html