gpt4 book ai didi

c - errno == ENOENT 是否足以检查 C 中是否存在文件?

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:50 24 4
gpt4 key购买 nike

在 Windows 8.1 上使用 PellesC。

我知道这个主题已经用很多解决方案解决了很多次。我已经阅读了说明 CreateFilePathFileExistsGetFileAttributes_access 用法的解决方案,我有点理解。

我还在 Quickest way to check whether or not file exists 问题的答案中读到了关于竞争条件的重要观点。和 What's the best way to check if a file exists in C? (cross platform) .

因此,如果我在 C 中使用 fopen() 打开一个文件,当它失败(出于任何原因)并返回 NULL 时;然后我可以进一步检查 errno == ENOENT 并满足于此并正确报告该文件不存在。

#include <stdio.h>
#include <string.h>
#include <errno.h>

int file_exists(char filename[]) {
int err = 0; //copy of errno at specific instance
int r = 0; //1 for exists and 0 for not exists
FILE *f = NULL;

//validate
if (filename == NULL) {
puts("Error: bad filename.");
return 0;
}

printf("Checking if file %s exists...\n", filename);

//check
errno = 0;
f = fopen(filename, "r");
err = errno;
if (f == NULL) {
switch (errno) {
case ENOENT:
r = 0;
break;
default:
r = 1;
}
printf("errno = %d\n%s\n", err, strerror(err));
} else {
fclose(f);
r = 1;
}

if (r == 0) {
puts("It does not.");
} else {
puts("It does.");
}

return r;
}

最佳答案

fopen 在打开文件之前需要做很多事情和检查。 ENOENT 暗示文件不存在,但文件不存在并不暗示ENOENT

一个文件可能不存在并且您会得到另一个错误,例如 EACCES 无法读取父目录。


另一方面,fopen 中的ENOENT 并不意味着其他进程甚至在 fopen 返回之前就无法创建该文件或者在检查 errno 等之前;这就是为什么 C11 添加了 x 标志以在独占模式下打开文件进行写入 - 如果文件已经存在则失败。


总结一下:如果您得到 ENOENT,则当您尝试打开该文件时该文件不存在。如果您遇到其他错误,那么彼此的错误代码将属于这 3 个类中的一个 - 可以肯定的是

  • 文件存在,或者
  • 不可能存在
  • 或者当时可能已经存在

开业时。如何处理这些其他错误取决于您和您所需的逻辑。一种简单的方法是拒绝继续处理,并向用户报告错误。

关于c - errno == ENOENT 是否足以检查 C 中是否存在文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com