[英]Why doesn't fopen open existing file? (returns NULL, errno ENOENT)
I have posted this to document my issue, see my self-answer below.我发布了这个来记录我的问题,请参阅下面的自我回答。
No matter what I try, fopen(...)
cannot open the existing file at the path which exists and returns NULL
.无论我尝试什么, fopen(...)
都无法在存在并返回NULL
的路径上打开现有文件。 I am executing the program from a bash script in ~/path
.我正在从~/path
的 bash 脚本执行程序。 The program file is stored at ~/path/to
.程序文件存储在~/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) is documented as capable of failing: fopen(3)被记录为能够失败:
Otherwise, NULL is returned and
errno
is set to indicate the error.否则,返回 NULL 并errno
以指示错误。
So you should at least code:所以你至少应该编码:
FILE* fp = fopen(filename, "r");
if (fp == NULL) { perror(filename); exit(EXIT_FAILURE); };
and fopen
won't even try to create a file that you open for reading only.并且fopen
甚至不会尝试创建您打开的只读文件。
As a rule of thumb, you always need to check against failure of fopen
(a minima like above), and report to your user (with the help of errno(3) , perror(3) , strerror(3) -used as strerror(errno)
- ...) the reason of that failure.根据经验,您始终需要检查fopen
失败(类似于上面的最小值),并向您的用户报告(在errno(3) 、 perror(3) 、 strerror(3) 的帮助下- 用作strerror(errno)
- ...) 失败的原因。 An educated user would be able to manage (perhaps with help from his sysadmin).受过教育的用户将能够管理(也许在他的系统管理员的帮助下)。
ENOENT
is documented in errno(3) to mean ENOENT
记录在errno(3)中表示
ENOENT
No such file or directory (POSIX.1-2001).ENOENT
没有这样的文件或目录(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.通常,当指定的路径名不存在,或者路径名的目录前缀中的组件之一不存在,或者指定的路径名是悬空的符号链接时,会导致此错误。
I find that explanation pretty clear.我觉得这个解释很清楚。 In your case, you probably don't have any path/
directory in your current working directory , or you do have path/to/my/
directory without any file
entry, etc (eg path/
exists but without to/
inside it) ....在您的情况下,您当前的工作目录中可能没有任何path/
目录,或者您确实有path/to/my/
目录而没有任何file
条目等(例如path/
存在但没有to/
在里面)。 ...
You could improve your program by showing not only the errno
(using strerror(errno)
or perror
) but also the working directory.您可以通过不仅显示errno
(使用strerror(errno)
或perror
)而且显示工作目录来改进您的程序。 See getcwd(3) .请参阅getcwd(3) 。 Or you could leave your user to guess it.或者您可以让您的用户猜测它。 Your user could have changed the working directory, eg with a cd
builtin command of his unix shell .您的用户可能已经更改了工作目录,例如使用他的unix shell的cd
内置命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.