c - 为什么 fopen 不打开现有文件? (返回 NULL,错误号 ENOENT)

标签 c segmentation-fault fopen

我发布此内容是为了记录我的问题,请参阅下面我的 self 回答。

无论我如何尝试,fopen(...) 都无法在存在的路径中打开现有 文件并返回NULL我正在从 ~/path 中的 bash 脚本执行程序。程序文件存储在~/path/to

int main(void) {
  const char* filename = "my/file"
  FILE* fp = NULL;
  fp = fopen(filename, "r"); // file is still NULL, segfaults on indirection
  if (!fp) exit(1);
  fclose(fp);
}

最佳答案

fopen(3)被记录为可能失败:

Otherwise, NULL is returned and errno is set to indicate the error.

所以你至少应该编码:

FILE* fp = fopen(filename, "r");
if (fp == NULL) { perror(filename); exit(EXIT_FAILURE); };

fopen甚至不会尝试创建您打开仅供阅读的文件。

根据经验,总是需要检查 fopen 是否失败(如上所述的最小值),并向您的报告用户(在 errno(3)perror(3)strerror(3) 的帮助下 - 用作 strerror(errno)- ...) 失败的原因。受过教育的用户将能够进行管理(也许在系统管理员的帮助下)。

ENOENT 记录在 errno(3) 中意思是

ENOENT No such file or directory (POSIX.1-2001).

Typically, this error results when a specified path‐ name does not exist, or one of the components in the directory prefix of a pathname does not exist, or the specified pathname is a dangling symbolic link.

我发现这个解释很清楚。就您而言,您当前的 working directory 中可能没有任何 path/ 目录。 ,或者您确实有 path/to/my/ 目录,没有任何 file 条目等(例如 path/ 存在,但没有 to/ 里面)....

您可以通过不仅显示 errno(使用 strerror(errno)perror)而且显示工作目录来改进您的程序。请参阅getcwd(3) 。或者您可以让您的用户猜测。您的用户可能更改了工作目录,例如使用他的 unix shellcd 内置命令.

关于c - 为什么 fopen 不打开现有文件? (返回 NULL,错误号 ENOENT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48740673/

相关文章:

matlab - 为什么 fopen 第一次失败,但第二次工作?

c - C语言命令行求三角形面积

c - MPI_Reduce() 程序出现段错误

c - 使用循环加载多个图像时出现段错误

c++ - 使用 iostream 消失的段错误

c - fprintf 不在 ^C 上写入,但在退出时写入

c - 请告诉我我的错误

c++ - OpenCV::ML - 是否可以告诉 openCV 我们要将数据的哪些部分发送到哪个神经元?

c - 将标准输出重定向到文件?

c - Linux fork() 和 wait()