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

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

#define _CRT_SECURE_NO_WARNINGS
#include 

#define SIZE 2
struct 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; iscanf("%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; iif (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; isizeof(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);
}


----------

你可能感兴趣的:(c)