c - 没有 fclose 的 readFile 函数

标签 c readfile

我有一个功能可以将新词添加到 .txt 文件中。我仍然需要做一个学习词汇的功能。有几次我必须读取文件,所以我尝试为它创建一个函数。

void readFile(FILE* fp, char *name){
  if((fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
}

而且我不想在这个函数中关闭文件,因为在其他函数中我会操作这个文件。

int main(){
  FILE *file;
  readFile(file,"verbs.txt");
  fclose(file);

  return 0;
}

如果我尝试那样关闭文件,我会得到核心转储。但是,如果 fclose 在 readFile 中,则效果很好。那么可以不使用 fclose() 来编写 readFile 函数吗?

最佳答案

将其更改为:

void readFile(FILE** fp, char *name){
  if((*fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
}

int main(){
  FILE *file=NULL;
  readFile(&file,"verbs.txt");
  //Use the file here after checking for NULL. 
  if (file != NULL)
      fclose(file); //check for NULL before closing.

  return 0;
}

关于c - 没有 fclose 的 readFile 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951987/

相关文章:

C: 内存池库?

c - 为什么我在这里遇到段错误?需要帮忙。想要将整数放入 char 指针数组

c++ - 基本数学函数的意外值

c - 使用C的MAC地址

c# - 从 Amazon s3 流中读取文本

python - 在生成器中返回参数

c++ - 结构数组的 typedef,其中一个字符数组作为结构的成员

c++ - 读取文件并在 C++ 中拆分行

c - 如何从c中的文件中正确读取某些字符串?

c++ - 文本文件中的 BellmanFord 未提供与手动输入相同的输出