剛剛做了個特定文件讀寫的小接口,裏面涉及到文件存在判定。寫的時候就直接用了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);
這主要是對於可訪問,可讀文件的判定,對於其他不可訪問/不可讀文件的判定是否有效需要測試的。