【问题标题】:Why a segmentation fault in feof()?为什么 feof() 中出现分段错误?
【发布时间】: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


【解决方案1】:

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

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

其次,您可以使用fread 的返回值,而不是使用feoffread 返回您传递给它的要读取的元素数。您可以检查此数字是否不同于 1。例如,

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

编辑 1: 按照 Weather Vane 的建议,将 while 循环更新为更惯用和更优雅的版本。

【讨论】:

  • 更惯用的可能是while (fread(&client, sizeof(struct Client), 1, f) == 1) { printf("Name: %s\n", client.name); }
  • 谢谢!我用feof 是因为我们在大学里学过它,但现在我明白它为什么不好了。
猜你喜欢
  • 2011-04-23
  • 2014-11-19
相关资源
最近更新 更多