【发布时间】:2020-01-16 12:37:22
【问题描述】:
我尝试在 C++ 中不存在的目录中打开一个文件,但由于某种原因,我的应用程序没有崩溃。我觉得这有点“奇怪”,因为我习惯了 C,等效程序确实会崩溃。这是我的 C++ 版本,后面是等效的 C 版本:
$ cat main.cpp
#include <fstream>
int main(int argc, char **argv)
{
std::ofstream f("/home/oren/NON_EXISTING_DIR/file.txt");
f << "lorem ipsum\n";
f.close();
printf("all good\n");
}
$ g++ main.cpp -o main
$ ./main
all good
当我尝试用 C 做同样的事情时,我得到一个段错误:
$ cat main.c
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *fl = fopen("/home/oren/NON_EXISTING_DIR/file.txt","w+t");
fprintf(fl,"lorem ipsum\n");
fclose(fl);
printf("all good\n");
}
$ gcc main.c -o main
$ ./main
Segmentation fault (core dumped)
这是为什么呢?
【问题讨论】:
-
您的程序崩溃不是因为它无法打开文件,而是因为它取消了对空指针的引用。
-
“不崩溃”并不意味着“它有效”。
-
任何程序在尝试打开不存在的文件时都不应崩溃。试图打开一个不存在的文件是一种普通的失败模式,任何文件打开程序都应该优雅地处理它。 C 程序必须在调用
fopen后检查返回的指针,如果指针为 NULL,则不尝试继续。 C++ 程序应该做类似的事情。