书中文件部分案例7.7

来源:互联网 发布:php 反射类 编辑:程序博客网 时间:2024/05/01 11:47

问题及代码:

/*书上p297案例7.7从键盘输入三明学生的数据,写入一个二进制文件stu_list.dat中,再读出这三名学生的成绩显示在显示器上*/#include <stdio.h>#include <stdlib.h>#define NUM 3typedef struct{    int num;    char name[10];    int age;    char addr[15];}student;int main(){    FILE*fp;    student stu1[NUM],stu2[NUM];    int i;    if((fp=fopen("stu_list.dat","wb+"))==NULL)    {        printf("Cannot open file!");        exit(1);    }    printf("Enter data of %d students\n",NUM);    for(i=0;i<NUM;i++)        scanf("%d%s%d%s",&stu1[i].num,stu1[i].name,&stu1[i].age,stu1[i].addr);    fwrite((void*)stu1,sizeof(student),NUM,fp);    rewind(fp);    printf("number\tname\tage\taddr\n");    for(i=0;i<NUM;i++)    {        fread((void*)&stu2[i],sizeof(student),1,fp);        printf("%d\t%s\t%d\t%s\n",stu2[i].num,stu2[i].name,stu2[i].age,stu2[i].addr);    }    fclose(fp);    return 0;}


0 0
原创粉丝点击