【发布时间】:2018-04-10 01:08:47
【问题描述】:
我有以下枚举和结构:
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);
}
我做错了什么?
【问题讨论】:
-
您确定它在
feof中存在段错误吗?你的fread调用是错误的,你正在破坏你的堆栈。你应该打电话给fread(&client, sizeof(struct Client), 1, f); -
您已准备好 1 类型的
struct Client记录。说fread(&client, sizeof(struct Client), 1, f); -
@MartinMagyar 为什么“while (!feof (file))”总是错的?
-
@MartinMagyar -- 最后一条记录被打印两次,因为you should never use
while (!feof(fp)) {}。
标签: c segmentation-fault feof