MFC 中的 CFile 及其派生類中沒有提供直接進行檔案的複制操作,因而要借助于SDK API;
SDK中的檔案相關函數常用的有CopyFile()、CreateDirectory()、DeleteFile()、MoveFile()
①、檔案的複制:CopyFile
若要複制檔案夾,可以在目标位置建立一檔案夾,然後将源檔案夾裡面的檔案進行周遊,一個一個的複制到目标檔案夾内即可!
②、檔案的重命名或移動 [适用于檔案夾]:
static CFile::Rename 重命名檔案;
MoveFile,※※※注意:該函數不僅可以移動檔案,還可以移動目錄,包括目錄中的檔案和子目錄,但是目錄的移動隻能限制在一個驅動器;
即:同一驅動器内為重命名操作,不同驅動器内為移動操作;
③、檔案的删除:CFile::Remove 或 DeleteFile
如果檔案有隻讀屬性怎麼辦?普通的方法還能删除成功嗎?
④、檔案屬性資訊的擷取:CFile::GetStatus
看看其内部 SDK API 的實作;
⑤、檔案屬性資訊的設定:CFile::SetStatus
看看其内部 SDK API 實作;
這回可以成功的将隻讀屬性的檔案删除了……方法就是去除檔案的隻讀屬性後再進行删除操作;
BOOL DelReadOnlyFile(LPCTSTR lpszPath)
{
DWORD dwRet = GetFileAttributes(lpszPath);
if (dwRet == INVALID_FILE_ATTRIBUTES) return FALSE;
if (dwRet & FILE_ATTRIBUTE_READONLY){
dwRet &= ~FILE_ATTRIBUTE_READONLY;
SetFileAttributes(lpszPath, dwRet);
}
return DeleteFile(lpszPath);
}
⑥、判斷檔案是否存在:方法也有很多種:
1>、_access 函數;
2>、CreateFile 函數;
3>、FindFirstFile 函數;
4>、GetFileAttributes 函數;
5>、PathFileExists(是 Shell Lightweight Utility APIs 函數:Header: Declared in Shlwapi.h Import Library: Shlwapi.lib)
這裡面給大家使用 GetFileAttributes 函數進行講解:
BOOL TargetIsExist(LPCTSTR lpszPath)
{
BOOL bRet = TRUE;
DWORD dwRet = GetFileAttributes(lpszPath);
if (dwRet == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND){
bRet = FALSE;
}
return bRet;
}
⑦、判斷給定路徑是檔案還是目錄:
1>、GetFileAttributes 函數;
2>、PathIsDirectory(是 Shell Lightweight Utility APIs 函數:Header: Declared in Shlwapi.h Import Library: Shlwapi.lib)
3>、……
這裡面給大家使用 GetFileAttributes 函數進行講解:
int TargetIsDirectory(LPCTSTR lpszPath)
{
int iRet = -1;
DWORD dwRet = GetFileAttributes(lpszPath);
if (dwRet == INVALID_FILE_ATTRIBUTES){
iRet = -1;
}else if (dwRet & FILE_ATTRIBUTE_DIRECTORY){
iRet = 1;
}else{
iRet = 0;
}
return iRet;
}