【问题标题】:fread failing to read a filefread 读取文件失败
【发布时间】:2018-05-10 14:19:11
【问题描述】:

我在这里有一个嵌套结构。

typedef struct 
{
    struct_one    one;  
    struct_two    two;
    struct_three  three;
} outermost_struct;

在函数中传递指向外部结构的指针

outermost_struct settings
readFileInStruct(settings_file, &settings)

我在struct中读取bin文件的函数

int readConfigIn2Struct
(
    char file_name[],
    outermost_struct*settings_mem_location
)
{
    FILE *ptr_file;
    ptr_file = fopen(file_name,"rb");
    if(ptr_file == NULL)
    {
        return -1;
    }
    fread(&(*settings_mem_location),sizeof(outermost_struct),1,ptr_file);
    fclose(ptr_file);
    return 0;
}

这里 fread 失败并返回到 main 函数。谁能告诉我为什么我的 fread 失败了? teh 文件的大小为 73kb,struct 有足​​够的内存来容纳整个文件。

现在我不是对整个文件执行一次 fread,而是尝试对每个结构执行 fread。 fread(&(*settings_mem_location),sizeof(struct_one),1,ptr_file);

这里 fread 正确地写入了 struct_one。现在我需要 fread 写入 struct_two。如何推进指针指向 struct_two?

【问题讨论】:

  • “嵌套结构”是什么意思?您可以edit您的问题并添加defined_nested_struct的定义以澄清。
  • 答案是:可能是的。当然,您仍然向我们展示了很多事实。
  • 它是如何失败的? struct_mem_location 分配了吗?文件是否打开? &(*a)(a+1)-1 一样有意义。
  • 不看返回值怎么知道 fread 做了什么?
  • @stark 我尝试使用返回值。 fread 永远不会返回,程序只是回到 main,所以我从来没有 fread 的返回值

标签: c struct fread


【解决方案1】:

免费调试详细的错误检查和日志记录。除此之外,包括额外的日志记录也很有帮助。

在您显示的代码的可能版本下方,反映了我上面的陈述:

int readConfigIn2Struct (
  char file_name[],
  outermost_struct * settings_mem_location)
{
#ifdef DEBUG      
  fprintf(stderr, "%s:%d - Entering %s with file_name = '%s', outermost_struct * = %p\n",
    __FILE__, __LINE__, __func__, file_name, (void*) settings_mem_location);
#endif

  assert(NULL != file_name);
  assert(NULL != settings_mem_location);

  int result = 0; /* be optimistic. */

  FILE *ptr_file = fopen(file_name, "rb");
  if (ptr_file == NULL)
  {
    result = -1;
  }
  else
  {
    size_t bytes_to_read = sizeof * settings_mem_location;
#ifdef DEBUG
    fprintf(stderr, "Bytes to read from '%s': %zu\", file_name, bytes_to_read);
#endif
    size_t bytes_read = fread(settings_mem_location, 1, bytes_to_read, ptr_file);

    if (bytes_read < bytes_to_read)
    {
      result = -1;

      if (feof(ptr_file))
      {
        fprintf(stderr, "Unexpectedly reached EOF after %zu bytes\", bytes_read);
      }
      else if (ferror(ptr_file))
      {
        fprintf(stderr, "An error occurred after reading %zu bytes\", bytes_read);
      }
    }

    fclose(ptr_file);
  }

#ifdef DEBUG
  fprintf(stderr, "%s:%d - Leaving %s with result = %d\n", __FILE__, 
    __LINE__, __func__, result);
#endif

  return result; /* One exit point per function is preferred over several. */
}

使用选项 -DDEBUG 编译以启用额外的日志记录,例如进入和退出。

使用选项-DNDEBUG 自动删除对assert() 的调用。

Details about assert() are in the documentation here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多