检查文件是否存在于C中的最佳方法是什么?

问题描述:

有没有比仅尝试打开文件更好的方法?

Is there a better way than simply trying to open the file?

int exists(const char *fname)
{
    FILE *file;
    if ((file = fopen(fname, "r")))
    {
        fclose(file);
        return 1;
    }
    return 0;
}


查找 access()函数,可在 unistd.h 中找到。您可以将函数替换为

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) != -1 ) {
    // file exists
} else {
    // file doesn't exist
}

您还可以使用 R_OK W_OK X_OK 代替 F_OK 来分别检查读取许可权,写入许可权和执行许可权,而不是是否存在,并且您可以将它们中的任何一个或在一起(即检查使用 R_OK | W_OK 获得写入权限

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

更新:请注意,在Windows上,您不能使用 W_OK 可靠地测试写入权限,因为访问功能未考虑DACL。 access(fname,W_OK)可能会返回0(成功),因为该文件没有设置只读属性,但是您仍然没有写该文件的权限

Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.