fread和fwrite对结构体数组从文件读入或写入

来源:互联网 发布:黑马大数据培训 编辑:程序博客网 时间:2024/06/05 16:15

从键盘输入4个学生数据,把他们转存到磁盘文件中去
重点内容

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#define SIZE 2struct student_type{    char name[10];    int num;    int age;    char addr[15];}stud[SIZE];main(){    void display();    void save();    printf("%s\n","liuwei");    int i;    for (i = 0; i<SIZE; i++)        scanf("%s%d%d%s", stud[i].name, &stud[i].num,        &stud[i].age, stud[i].addr);    save();    display();}void save(){    FILE *fp;    int  i;    if ((fp = fopen("d:\\stu_dat.data", "wb")) == NULL)    {        printf("cannot open file\n");        return;    }    for (i = 0; i<SIZE; i++)    if (fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)        printf("file write error\n");    fclose(fp);}void display(){    FILE *fp;    int  i;    if ((fp = fopen("d:\\stu_dat.data", "rb")) == NULL)    {        printf("cannot open file\n");        return;    }    for (i = 0; i<SIZE; i++)    {        fread(&stud[i], sizeof(struct student_type), 1, fp);        printf("%s",stud[i].name);        printf("%-10s %4d %4d %-15s\n", stud[i].name,            stud[i].num, stud[i].age, stud[i].addr);    }    fclose(fp);}----------
0 0