有没有比简单地try 打开文件更好的方法呢?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
有没有比简单地try 打开文件更好的方法呢?
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
}
您还可以使用R_OK
、W_OK
和X_OK
来代替F_OK
来判断读权限、写权限和执行权限(分别),而不是判断它们是否存在,您可以同时使用R_OK
、W_OK
和X_OK
来判断读权限、写权限和执行权限(即使用R_OK|W_OK
来判断读权限和写权限)
Update:请注意,在Windows上,您不能使用W_OK
来可靠地测试写权限,因为访问函数没有考虑DACL.access( fname, W_OK )
可能会返回0(成功),因为该文件没有设置只读属性,但您可能仍然没有写入该文件的权限.