我有一个功能可以将新词添加到 .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/