遞歸拷貝目錄與刪除目錄 WindowsAPI C++

/*判斷一個路徑是不是已存在的目錄*/
bool IsDirectory(const std::wstring& pstrPath)
{
	DWORD dw = GetFileAttributes(pstrPath.c_str());
	if (dw == INVALID_FILE_ATTRIBUTES)
	{
		return false;
	}
	return (dw & FILE_ATTRIBUTE_DIRECTORY) != 0;
}

/*複製目錄及目錄中的全部內容*/
bool CopyFolder(const std::wstring& pstrFolder, const std::wstring& pstrDest)
{
	/*檢查輸入目錄是不是合法目錄*/
	if (!IsDirectory(pstrFolder))
	{
		return false;
	}
	if (!IsDirectory(pstrDest))
	{
		CreateDirectoryW(pstrDest.c_str(), NULL);
	}

	std::wstring strFind = pstrFolder;
	if (*strFind.rbegin() != L'\\' &&
		*strFind.rbegin() != L'/')
	{
		strFind.append(L"\\");
	}
	strFind.append(L"*.*");
	std::wstring strDest = pstrDest;
	if (*strDest.rbegin() != L'\\' &&
		*strDest.rbegin() != L'/')
	{
		strDest.append(L"\\");
	}


	/*打開文件查找,查看源目錄中是否存在匹配的文件*/
	/*調用FindFile後,必須調用FindNextFile才能得到查找文件的信息*/
	WIN32_FIND_DATA wfd;
	HANDLE hFind = FindFirstFileW(strFind.c_str(), &wfd);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		return false;
	}
	do
	{
		std::wstring strSubFolder;
		std::wstring strDestFolder;
		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (wfd.cFileName[0] == L'.')
			{
				continue;
			}
			else
			{
				strSubFolder = strFind.substr(0, strFind.length() - 3) + wfd.cFileName;
				strDestFolder = strDest + +wfd.cFileName;
				CopyFolder(strSubFolder, strDestFolder);
			}
		}
		else
		{
			strSubFolder = strFind.substr(0, strFind.length() - 3) + wfd.cFileName;
			strDestFolder = strDest + +wfd.cFileName;
			CopyFileW(strSubFolder.c_str(), strDestFolder.c_str(), FALSE);
		}
	} while (FindNextFileW(hFind, &wfd));

	/*刪除空目錄*/
	FindClose(hFind);
	return true;
}

/*刪除目錄及目錄中的全部內容*/
bool DeleteFolder(const std::wstring& pstrFolder, bool recursive)
{
	/*檢查輸入目錄是不是合法目錄*/
	if (!IsDirectory(pstrFolder))
	{
		return false;
	}

	std::wstring strFind = pstrFolder;
	if (*strFind.rbegin() != L'\\' &&
		*strFind.rbegin() != L'/')
	{
		strFind.append(L"\\");
	}
	strFind.append(L"*.*");

	/*打開文件查找,查看源目錄中是否存在匹配的文件*/
	/*調用FindFile後,必須調用FindNextFile才能得到查找文件的信息*/
	WIN32_FIND_DATA wfd;
	HANDLE hFind = FindFirstFileW(strFind.c_str(), &wfd);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		return false;
	}
	do
	{
		std::wstring strSubFolder;
		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (wfd.cFileName[0] == L'.')
			{
				continue;
			}
			else if (recursive)
			{
				strSubFolder = strFind.substr(0, strFind.length() - 3) + wfd.cFileName;
				DeleteFolder(strSubFolder, recursive);
			}
		}
		else
		{
			strSubFolder = strFind.substr(0, strFind.length() - 3) + wfd.cFileName;
			DeleteFileW(strSubFolder.c_str());
		}
	} while (FindNextFileW(hFind, &wfd));

	/*刪除空目錄*/
	FindClose(hFind);
	return RemoveDirectoryW(pstrFolder.c_str()) == TRUE;
}
相關文章
相關標籤/搜索