刚刚做了个特定文件读写的小接口,里面涉及到文件存在判定。写的时候就直接用了C++的文件流完成了,如下:
bool exists(const std::string& name)
{//C++
ifstream f(name.c_str());
return f.good();
}//自动释放资源,所以不用明确调用关闭函数
后面检查代码的时候,想起几种其他的方法,再去网上找了些资料,统计下,发现这个方法还是有点多的,特记录下来。上面方法的另一种写法
bool exists (string const& p) { return ifstream{p}; }
在C中可以用的
bool exists (char* name)
{//C
if (FILE *file = fopen(name, "r"))
{
fclose(file);
return true;
} else
{
return false;
}
}
下面的方法网上搜到的,本人没有验证过
bool exists (char* name)
{
return ( access(name, F_OK ) != -1 );
}
bool exists (char* name)
{//C
struct stat buffer;
return (stat (name, &buffer) == 0);
}
由于本人主要在windows系统上做项目的,顺便也就记录了win api相关的
bool exists (char* name)
{
OFSTRUCT of_struct;
return OpenFile(name,&of_struct,OF_EXIST)!=INVALID_HANDLE_VALUE&& of_struct.nErrCode == 0;
}
bool exists (char* name)
{
HANDLE hFile = CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != NULL && hFile != INVALID_HANDLE)
{
CloseFile(hFile);
return true;
}
return false;
}
bool exists (char* name)
{//标准做法
return GetFileAttributes(name) != INVALID_FILE_ATTRIBUTES;
}
其中最后一个也是最广泛使用的方法,被称为是标准方法。
Win api能做,MFC也有被封装之后的方法
CFileStatus FileStatus;
BOOL bFileExists = CFile::GetStatus(FileName,FileStatus);
这主要是对于可访问,可读文件的判定,对于其他不可访问/不可读文件的判定是否有效需要测试的。