欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

删除文件夹和文件夹下的文件

程序员文章站 2024-03-17 12:04:10
...

C++没有删除文件的功能,可借助windows API实现该功能,还可以依据调用C运行库函数实现删除功能。

删除文件的函数为DeleteFile

删除文件夹的函数为RemoveDirectory

参考自:https://blog.csdn.net/u012159849/article/details/79410531

删除文件夹和文件夹下的子文件函数实现如下:

BOOL DeleteDirectory(CString strPathName)
{
	//delete all files in this strPathName directory
	//note: when the file's attribute is read only, call DeleteFile fun will get 5 error.
	//need to modify file attribute
	BOOL res = FALSE;
	CFileFind tempFind;
	DWORD errorCode;
	TCHAR sTempFileFind[MAX_PATH] = { 0 };
	wsprintf(sTempFileFind, _T("%s\\*.*"), strPathName);
	BOOL IsFinded = tempFind.FindFile(sTempFileFind);
	while (IsFinded)
	{
		IsFinded = tempFind.FindNextFile();
		if (!tempFind.IsDots())
		{
			TCHAR sFoundFileName[MAX_PATH] = { 0 };
			_tcscpy(sFoundFileName, tempFind.GetFileName().GetBuffer(MAX_PATH));
			//when current filename is directory,
			if (tempFind.IsDirectory())
			{
				TCHAR sTempDir[MAX_PATH] = { 0 };
				wsprintf(sTempDir, _T("%s\\%s"), strPathName, sFoundFileName);
				if (!DeleteDirectory(sTempDir))
				{
					errorCode = GetLastError();
					TRACE(_T("Delete %s Folder Fail in %s path, error is %d.\n"), sTempDir, strPathName, errorCode);
					tempFind.Close();
					return FALSE;
				}
			}
			else
			{
				TCHAR sTempFileName[MAX_PATH] = { 0 };
				wsprintf(sTempFileName, _T("%s\\%s"), strPathName, sFoundFileName);
				//change file attribute to FILE_ATTRIBUTE_READONLY
				DWORD dwAttribute = GetFileAttributes(sTempFileName);
				if (dwAttribute & FILE_ATTRIBUTE_READONLY)
				{
					dwAttribute &= ~FILE_ATTRIBUTE_READONLY;
					SetFileAttributes(sTempFileName, dwAttribute);
				}
				if (!DeleteFile(sTempFileName))
				{
					errorCode = GetLastError();
					TRACE(_T("Delete %s File Fail in %s path, error is %d.\n"), sTempFileName, strPathName, errorCode);
					tempFind.Close();
					return FALSE;
				}
			}
		}
	}
	tempFind.Close();
	//delete this folder after delete all files in the folder
	if (!RemoveDirectory(strPathName))
	{
		errorCode = GetLastError();
		TRACE(_T("Delete %s Folder Fail, error is %d.\n"), strPathName, errorCode);
		return FALSE;
	}
	return TRUE;
}

函数调用如下:

CString deleteFolderName = L"D:\\MyDeleteFile";
if (deleteFolderName == L"")
{
	TRACE(_T("Folder Directory Does Not Exist.\n"), deleteFolderName);
	return FALSE;
}
if (!DeleteDirectory(deleteFolderName))
{
	TRACE(_T("Delete %s Folder Directory Fail.\n"), deleteFolderName);
	return FALSE;
}

参考自:https://blog.csdn.net/ss33sss/article/details/92771861

特别要注意:

当文件为只读时,不能直接被删除,需要修改其属性,去掉只读性。

调用SetFileAttributes函数。

参考自:https://blog.csdn.net/weixin_36587312/article/details/75096650