c语言怎样将结构体数组写入文件 (c语言读取二进制文件存储到数组)

结构体数组可以按串或按块读写到文本文件或二进制文件。

如果是按块写到文件时,则读时也要按块读到内存,二者要一致,即都是按块操作。因为其数据类型的长度是一致,所以操作时不会存在位置错乱,且可以随机读写,如读写结构体数据的某一条记录。

#include <stdio.h> 
typedef struct student
{
    int num;
    char name[30];
    char sex;
    float math;
    float english;
    float chinese;
}Student;

#define OPEN_ERR(fp) if(fp == NULL)\
{\
    printf("open error\n");\
    return -1;\
}

int main()
{
    FILE* fp = fopen("stu.data","wb+");
    OPEN_ERR(fp);
    Student stu[] = {
        {1001,"bob1",'m',100,30,20},
        {1002,"bob2",'f',100,30,20},
        {1003,"bob3",'m',100,30,20}
    };
    int arrSize = sizeof stu / sizeof *stu;

    // 结构体按块读写
    for(int i=0; i<arrSize; i++)
    {
        fwrite((void*)&stu[i],sizeof(Student),1,fp); // 1表示写一次
    }
    rewind(fp); // 记录位置的写指针从结构偏移到开头
    Student tmp;
    for(i=0; i<arrSize; i++)
    {
        fread((void*)&tmp,sizeof(Student),1,fp); // 1表示读一次
        printf("num: %d name:%s sex:%c math:%.2f english:%.2f chinese:%.2f\n",
            tmp.num,tmp.name,tmp.sex,tmp.math,tmp.english,tmp.chinese);
    }
    fclose(fp);
    
    // 结构体按串读写
    FILE* fpa = fopen("stu.txt","w+");
    OPEN_ERR(fpa);
    for(i=0; i<arrSize; i++)
    {
        fprintf(fpa,"%d,%s,%c,%.2f,%.2f,%.2f\n",
            stu[i].num,stu[i].name,stu[i].sex,stu[i].math,stu[i].english,stu[i].chinese);
    }
    //fflush(fpa);
    rewind(fpa);
    Student tp;
    for(i=0; i<arrSize; i++)
    { // 字符串在写入时并未写入'\0',所以按格式读字符串时要适当处理,不然后将其与它后面的字符全部读出
        fscanf(fpa,"%d,%4s,%c,%f,%f,%f", // 字符串读取的长度这里做了简化处理,建议使用strtok()
            &tp.num,&tp.name,&tp.sex,&tp.math,&tp.english,&tp.chinese);
        printf("num: %d name:%s sex:%c math:%.2f english:%.2f chinese:%.2f\n",
            tp.num,tp.name,tp.sex,tp.math,tp.english,tp.chinese);
    }
    fclose(fpa);
    getchar();
    return 0;
}

-End-