文件指针

C++还提供了一种FILE的文件结构指针类型,FILE是在<cstdio>或<stdio.h>里定义的,使用时要包含这个库。

例一:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <cstdio>
using namespace std;

int main(){
    FILE *fin, *fout;
    fin=fopen("in.txt","r");
    fout=fopen("out.txt","w");
    
    int n;
    fscanf(fin,"%d",&n);
    n++;
    fprintf(fout,"%d",n);
    printf("%d",n);
    
    return;
}

例二:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include<cstdio>
using namespace std;
int main()
{
   FILE *fin,*fout;
   fin = fopen("in.txt","r");                    //定义输入文件名
   fout = fopen("out.txt","w");              //定义输出文件名
   int temp,sum=0;
   while (fscanf(fin,"%d",&temp)==1)   //从输入文件中读入数据
     {
        sum=sum+temp;
     }
   fprintf(fout,"%d\n",sum);                   // cout<<sum<<endl;
   fclose(fin);fclose(fout);                     //关闭文件,可省略
   return 0;                                                   
}

Scroll to Top