1.删除指定文件
第一种方法:定义一个文件类对象来操作
CFile TempFile;
TempFile.Remove(指定文件名);
第二种方法:
DeleteFile("c:\\abc\\test.exe ");//MFC框架中可直接调用此函数
2.删除目录
_rmdir()
DeleteDirectory(sTempDir)
RemoveDirectory(sTempDir)
//删除文件夹目录(非空)
方法一
bool DeleteDirectory( CString DirName)
{
AfxMessageBox("执行删除文件夹:"+DirName);
CString PUBPATH;
PUBPATH=DirName;
CFileFind tempFind;
DirName+="\\*.*";
BOOL IsFinded=(BOOL)tempFind.FindFile(DirName);
while(IsFinded)
{
IsFinded=(BOOL)tempFind.FindNextFile();
if(!tempFind.IsDots())
{
CString strDirName;
strDirName+=PUBPATH;
strDirName+="\\";
strDirName+=tempFind.GetFileName();
AfxMessageBox("strDirName :"+strDirName);
if(tempFind.IsDirectory())
{
//strDirName += PUBPATH;
DeleteDirectory(strDirName);
}
else
{
SetFileAttributes(strDirName,FILE_ATTRIBUTE_NORMAL); //去掉文件的系统和隐藏属性
DeleteFile(strDirName);
}
}
}
tempFind.Close();
if(!RemoveDirectory(PUBPATH))
{
return false ;
}
AfxMessageBox("文件夹删除成功...");
return true;
}
方法二
bool DeleteDirectory( char* DirName)
{
HANDLE hFirstFile = NULL;
WIN32_FIND_DATA FindData;
char currdir[MAX_PATH] = {0};
sprintf(currdir, "%s\\*.*", DirName);
hFirstFile = ::FindFirstFile(currdir, &FindData);
if( hFirstFile == INVALID_HANDLE_VALUE )
return false;
BOOL bRes = true;
while(bRes)
{
bRes = ::FindNextFile(hFirstFile, &FindData);
if( (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) //发现目录
{
if( !strcmp(FindData.cFileName, ".") || !strcmp(FindData.cFileName, "..") ) //.或..
continue;
else
{
char tmppath[MAX_PATH] = {0};
sprintf(tmppath, "%s\\%s", DirName, FindData.cFileName);
DeleteDirectory(tmppath);
}
}
else //发现文件
{
char tmppath[MAX_PATH] = {0};
sprintf(tmppath, "%s\\%s", DirName, FindData.cFileName);
::DeleteFile(tmppath);
}
}
::FindClose(hFirstFile);
if(!RemoveDirectory(DirName))
{
return false ;
}
return true;
}