2017-10-28 109 views
0

我有以下枚举和struct:为什么在feof()中出现分段错误?

enum Destination { unknown = 0, hosok, parlament, var }; 

struct Client 
{ 
    char name[30]; 
    char email[30]; 
    char phone_num[11]; 
    int client_num; 
    enum Destination destination; 
    struct tm registration_date; 
}; 

当我调用下面的方法,它会读取第一个结构并打印它的名字,然后我得到一个分段错误。

void list_clientss() 
{ 
    FILE *f = fopen(filename, "r"); 
    if(f == NULL) 
    { 
    perror("Error"); 
    } 
    struct Client client; 
    while(!feof(f)) 
    { 
    fread(&client, sizeof(struct Client), sizeof(struct Client), f); 
    printf("Name: %s\n", client.name); 
    } 
    fclose(f); 
} 

我错了什么?

+4

[为什么“while(!feof(file))”总是出错?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) –

+2

你确定它在'feof'中进行了吗?你的'fread'电话是错误的,你正在摧毁你的筹码。你应该调用'FREAD(客户端的sizeof(结构客户端),1,F);' – Cornstalks

+0

你'型结构Client'的准备_1_记录。说'FREAD(客户端的sizeof(结构客户端),1,F);' – Gene

回答

2

首先,你的fread调用应该是如下:

fread(&client, sizeof(struct Client), 1, f); 

其次,而不是使用feof,你可以使用的fread返回值。 fread返回您传递给它的元素的数量。你可以检查这个数字是不是一个。例如,

while (fread(&client, sizeof(struct Client), 1, f) == 1) { 
    printf("Name: %s\n", client.name); 
} 

编辑1:更新while循环更地道,优雅版本风向标建议。

+0

更惯用可能是'而(的fread(客户机,的sizeof(结构客户端),1,F)== 1){printf的( “名称:%s \ n” 个,client.name); }' –

+0

谢谢!我用'feof'是因为我们在大学学习它,但现在我明白它为什么不好。 – prophet4955

相关问题