检查文件是否存在于 C 中的最佳方法是什么? [英] What's the best way to check if a file exists in 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 ) == 0 ) {
// file exists
} else {
// file doesn't exist
}
您也可以使用 R_OK
、W_OK
和 X_OK
代替 F_OK
来检查读取权限,写权限和执行权限(分别)而不是存在,您可以将它们中的任何一个 OR 在一起(即使用 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.
这篇关于检查文件是否存在于 C 中的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!