在C中使用指针的文件指针进行结构化

时间:2014-10-30 11:38:08

标签: c memory-leaks

我正在使用这个结构来处理指针的指针:

typedef struct resources{
  FILE *file;
}Resources;

这将关闭文件:

int resources_free(){
  fclose(resource->file);
  FREE(resource);
  return 0;
}

这个函数将添加一个指向结构的指针的新指针:

int new_file_resource(FILE *file)){
  resource = malloc(sizeof(Resources));
  resource->file = malloc(sizeof(file));
  resource->file = *file;
  return 0;
}

但由于某种原因,我得到“在退出时使用:1个块中的4个字节”。

1 个答案:

答案 0 :(得分:3)

file已经是一个指针,你不需要为它预留空间:

int new_file_resource(FILE *file)){
  resource = malloc(sizeof(TResources));
  resource->file = malloc(sizeof(file)); /* remove this line */
  resource->file = *file; /* should be resource->file = file; */
  return 0;
}

另请注意,return 0未检查malloc的结果,我建议:

int new_file_resource(FILE *file)){
  resource = malloc(sizeof(TResources));
  if (resource) {
    resource->file = file;
    return 0;
  } else {
    return 1;
  }
}
  

如果我使用多个文件,我需要在struct“FILE上插入   * file_one,* file_two“?有什么方法可以动态地执行此操作吗?

你需要一个指向指针的指针:

#define NFILES 2
FILE **f;

f = malloc(sizeof(*f) * NFILES);
f[0] = fopen("a.txt", "r");
f[1] = fopen("b.txt", "r");