【发布时间】:2018-09-05 06:20:52
【问题描述】:
在 Windows 8.1 上使用 PellesC。
我知道这个话题已经用很多解决方案解决了很多次。我已经阅读了说明CreateFile、PathFileExists、GetFileAttributes、_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;
}
【问题讨论】:
-
如果您想向用户报告错误原因,那么使用
errno确实是您想要的。如果您想知道文件是否存在,那么缺少ENOENT并不能保证(例如,您可能会收到另一个错误,例如EPERM,或者该文件可能已被创建作为fopen调用的一部分,或...)。你能更详细地描述一下你想要达到的目标吗? -
我将发布代码。等一下。