如何从文件中读取struct元素?

时间:2017-04-18 15:57:17

标签: c

您好我有以下结构:

struct points{
    int round[11];
    int sum;
};

struct student{
    char studid[7];
    char *s_name;
    char *f_name;
    struct points p_points;
};

我正在创建一个结构数组,每个结构代表一个学生。当我退出程序时,我将使用以下函数将该数组保存到文件中:

int save_file(struct student *array, int size, const char *filename){
    struct student *object=malloc(size*sizeof(struct student));
    for(int i=0;i<size;i++){
        object[i].f_name=malloc(strlen(array[0].etunimi)+1);
        object[i].s_name=malloc(strlen(array[0].sukunimi+1));
        strcpy(object[i].f_name,array[0].etunimi);
        strcpy(object[i].s_name,array[0].sukunimi);
        strcpy(object[i].studid,array[0].opnro);
        object[i].points=array[0].points;
    }
    FILE * file= fopen(filename, "wb");
    if (file != NULL) {
        fwrite(object, size*sizeof(struct student), 1, file);
        fclose(file);
    }
    for(int x=0;x<size;x++){
        free(object[x].etunimi);
        free(object[x].sukunimi);
    }
    free(object);
    return 1;
}

当我想修改记录并加载文件时,我遇到了问题。我不知道如何为object [i] .f_name和object [i] .s_name分配内存,我不知道文件中数组的大小。我的功能现在看起来像这样:

int read_file(const char *filename){
    struct student *object2=malloc(sizeof(struct student));
    FILE * file= fopen("output", "rb");
    if (file != NULL) {
        fread(object2, sizeof(struct student), 1, file);
        fclose(file);
    }
    print_situation(object2,1);
    return 1;
}

如何检查文件中数组的大小,并从文件中获取f_name和s_name的长度,以便正确分配内存?

0 个答案:

没有答案
相关问题