c - 使用 FILE 类型的结构时接收段错误 - C

标签 c struct typedef

尝试使用 fopen 和包含 FILE 类型的结构打开文件时,我不断收到段错误。刚接触 C 语言,如果这是一个菜鸟问题,我很抱歉。 结构体代码:

  typedef struct _FileInternal {
  FILE* fp;
  char mem[2];
} FileInternal;

// file handle type
typedef FileInternal* File;

打开文件的代码:

File open_file(char *name) {
  File a;

  fserror=NONE;
  // try to open existing file
  a->fp=fopen(name, "r+");
  if (! a->fp) {
    // fail, fall back to creation
    a->fp=fopen(name, "w+");
    if (! a->fp) {
      fserror=OPEN_FAILED;
      return NULL;
    }
  }
  return a;
}

尝试 文件f; f=fopen("newfile.dat"); 返回错误

非常感谢任何帮助!

最佳答案

File 是一个指针类型,它使 a 成为一个指针。 a 永远不会初始化为指向有效的 FileInternal 结构,因此取消引用它可能会导致段错误。

关于c - 使用 FILE 类型的结构时接收段错误 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268033/

相关文章:

大多数语言的行和列索引约定

c++ - 生成运行时递归调用树的工具

c++ - C++-候选函数不可行: no known conversion from 'struct ' to 'struct (&)'

c - 来自结构数组的函数调用

c - bison 和 flex 的 Typedef 问题

arrays - 计算 C 中一致字符串的数量

c - Fscanf 给出段错误

c++ - 静态常量对象

c++ - 使用 using 或 typedef 减少模板参数

c++ - 没有匹配的函数用于调用c++