C检查文件是否存在

The*_*GiG 14 c c89

在我必须在C89标准中执行的项目中,我必须检查文件是否存在.我该怎么做呢?

我想过要用

FILE *file;
if ((file = fopen(fname, "r")) == NULL)
{
  printf("file doesn't exists");
}
return 0;
Run Code Online (Sandbox Code Playgroud)

但我认为可能有更多的情况,然后文件不存在,将执行fopen == NULL.

我该怎么做呢?我宁愿不使用包含而不是.

oni*_*ake 14

如果您不能在您的环境中使用stat()(这绝对是更好的方法),只需评估errno.别忘了包含errno.h.

FILE *file;
if ((file = fopen(fname, "r")) == NULL) {
  if (errno == ENOENT) {
    printf("File doesn't exist");
  } else {
    // Check for other errors too, like EACCES and EISDIR
    printf("Some other error occured");
  }
} else {
  fclose(file);
}
return 0;
Run Code Online (Sandbox Code Playgroud)

编辑:忘了将fclose包装成else

  • 为什么`stat()`是一个更好的方法``access()`with`F_OK`? (2认同)