gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:13:33 26 4
gpt4 key购买 nike

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

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

最佳答案

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

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/230062/

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