原文網址:http://shijuanfeng.blogbus.com/logs/100675115.html
第一種方法:定義一個文件類對象來操作
CFile TempFile;
TempFile.Remove(指定文件名);
第二種方法: 使用系統函數 DeleteFile( LPCSTR filename )刪除文件 _rmdir(),刪除目錄 DeleteDirectory(sTempDir); 刪除目錄 RemoveDirectory(sTempDir);刪除目錄
eg: DeleteFile( char *tempFileName);
令注:若要清空文件,但保留目錄用: system(“del C:\temp”); // 清空了C:\temp中的所有文件,但是不會清楚文件夾下的子目錄,而且會彈出:是否刪除的Doc框
//刪除文件夾目錄(非空) 上面提到的刪除目錄的方法只能刪除空目錄(即文件夾),如果目錄下有文件或者子目錄,就不能刪除了,VC里好像沒有直接的函數,只能手動寫個函數來刪除了,下面提供一個刪除非空目錄的方法:
bool DeleteDirectory(char* sDirName)
{
CFileFind tempFind;
char sTempFileFind[200];
strcpy(sTempFileFind, sDirName);
strcat(sTempFileFind, “\\*.*”);
BOOL IsFinded = tempFind.FindFile(sTempFileFind);
while (IsFinded)
{
IsFinded = tempFind.FindNextFile();
char sFoundFileName[200];
strcpy(sFoundFileName,tempFind.GetFilePath());
DeleteFile(sFoundFileName);
}
tempFind.Close();
}
清空整個文件夾的內容(包括子文件夾),但保留該文件夾
void CRelCtrlDlg::DeleteDirectory(char* sDirName)
{
char sPath[200];
strcpy(sPath, sDirName);
CFileFind ff;
BOOL bFound;
char sTempFileFind[200];
strcpy(sTempFileFind, sPath);
strcat(sTempFileFind, “\\*.*”);
bFound = ff.FindFile(sTempFileFind);
while(bFound)
{
bFound = ff.FindNextFile();
CString sFilePath = ff.GetFilePath();
if(ff.IsDirectory())
{
if(!ff.IsDots())
DeleteDirectory((LPSTR)(LPCTSTR)sFilePath);
}
else
{
if(ff.IsReadOnly())
{
SetFileAttributes(sFilePath, FILE_ATTRIBUTE_NORMAL);
}
DeleteFile(sFilePath);
}
}
ff.Close();
SetFileAttributes(sPath, FILE_ATTRIBUTE_NORMAL);
if (!strcmp(sPath,sDirName))
{
return;
}
RemoveDirectory(sPath);
}