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

15 浏览
0 Comments

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

是否有更好的方法来打开文件?

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

admin 更改状态以发布 2023年5月25日
0
0 Comments

像这样使用stat

#include    // stat
#include     // bool type
bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

像这样调用它:

#include       // printf
int main(int ac, char **av) {
    if (ac != 2)
        return 1;
    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);
    return 0;
}

0
0 Comments

查找在unistd.h中找到的access()函数。您可以用以下内容替换您的函数

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

在Windows(VC)中,unistd.h不存在。要使其工作,需要定义:

#ifdef WIN32
#include 
#define F_OK 0
#define access _access
#endif

您还可以使用R_OKW_OKX_OK替代F_OK,以检查读取权限、写入权限和执行权限(分别)而不是存在性,您可以将任何一种权限OR在一起(即使用R_OK|W_OK检查读取和写入权限)

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

0