fprintfAndFscanf简单操作

 

C语言fscanf和fprintf函数的用法详解(格式化读写文件)(代码转载)

 

#include<stdio.h>

#define N 2

struct stu{

    char name[10];

    int num;

    int age;

    float score;

} boya[N], boyb[N], *pa, *pb;

 

int main()

{

    FILE *fp;

    int i;

    pa=boya;

    pb=boyb;

    if( (fp=fopen("D:\\demo.txt","wt+")) == NULL ){

        puts("Fail to open file!");

        exit(0);

    }

 

    //从键盘读入数据,保存到boya

    printf("Input data:\n");

    for(i=0; i<N; i++,pa++){

        scanf("%s %d %d %f", pa->name, &pa->num, &pa->age, &pa->score);   

    }

    pa = boya;

    //将boya中的数据写入到文件

    for(i=0; i<N; i++,pa++){

        fprintf(fp,"%s %d %d %f\n", pa->name, pa->num, pa->age, pa->score);   

    }

    //重置文件指针

    rewind(fp);

    //从文件中读取数据,保存到boyb

    for(i=0; i<N; i++,pb++){

        fscanf(fp, "%s %d %d %f\n", pb->name, &pb->num, &pb->age, &pb->score);

    }

    pb=boyb;

    //将boyb中的数据输出到显示器

    for(i=0; i<N; i++,pb++){

        printf("%s  %d  %d  %f\n", pb->name, pb->num, pb->age, pb->score);

    }

    fclose(fp);

    return 0;

}

 原文链接:http://c.biancheng.net/view/2073.html

posted @ 2020-08-25 09:42  萧海~  阅读(207)  评论(0编辑  收藏  举报