我有以下的枚举和结构:
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);
}我做错什么了?
发布于 2017-10-28 17:04:14
首先,您的fread电话应该如下:
fread(&client, sizeof(struct Client), 1, f);其次,您可以使用fread的返回值,而不是使用fread。fread返回要读取已传递给它的元素的数量。您可以检查这个数字是否与一个不同。例如,
while (fread(&client, sizeof(struct Client), 1, f) == 1) {
printf("Name: %s\n", client.name);
}编辑1:更新while循环到更地道和更优雅的版本,就像天气叶片建议的那样。
https://stackoverflow.com/questions/46991788
复制相似问题