gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:16:20 25 4
gpt4 key购买 nike

有没有比简单地尝试打开文件更好的方法?

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

最佳答案

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

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

在 Windows (VC) 下 unistd.h 不存在。为了使其工作,有必要定义:

#ifdef WIN32
#include <io.h>
#define F_OK 0
#define access _access
#endif

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

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

关于c - 检查 C 中文件是否存在的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56640026/

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