什么是检查文件是否用C存在的最好方法? (跨平台) [英] What's the best way to check if a file exists in C? (cross platform)
问题描述
有没有更好的办法不是简单地试图打开该文件?
INT存在(为const char * FNAME)
{
FILE *文件;
如果(文件= FOPEN(FNAME,R))
{
FCLOSE(文件);
返回1;
}
返回0;
}
中查找接入()
函数,在 unistd.h中<发现/ code>。您可以取代你的功能
如果(接入(FNAME,F_OK)!= -1){
// 文件已存在
}其他{
//文件不存在
}
您也可以使用 R_OK
, W_OK
和 X_OK
在 F_OK
检查读取权限,写权限和执行(分别)的权限,而不是存在,你可以或其中任何一起(即检查同时读取的和的使用 R_OK写入权限| W_OK
)
的更新的:请注意,在Windows上,你不能使用 W_OK
来可靠地测试的写权限,因为访问功能用不了的DACL考虑。 接入(FNAME,W_OK)
可能会返回0(成功),因为该文件不具有只读属性设置,但你仍然可能没有权限写入到文件
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;
}
Look up the access()
function, found in unistd.h
. You can replace your function with
if( access( fname, F_OK ) != -1 ) {
// file exists
} else {
// file doesn't exist
}
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
)
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屋!