C++文件操作自定义函数

//////////////////////////////////////////////////////////////////////////
 
 //检查某个文件,或目录是否存在
 
 //bIsDirCheck=TRUE指定检查的对象是目录,反之文件
 
 BOOL FileExists(LPCTSTR lpszFileName,BOOL bIsDirCheck)
 
 {
 
 	//试图取得文件属性
 
 	DWORD dwAttributes=GetFileAttributes(lpszFileName);
 
 	if (dwAttributes==0xFFFFFFFF)//INVALID_FILE_ATTRIBUTES
 
 	{
 
 		return FALSE;
 
 	}
 
 	if((dwAttributes&&FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY)
 
 	{
 
 		if (bIsDirCheck)
 
 		{
 
 			return TRUE;
 
 		}
 
 		else
 
 		{
 
 			return FALSE;
 
 		}
 
 	}
 
 	else
 
 	{
 
 		if (!bIsDirCheck)
 
 		{
 
 			return TRUE;
 
 		}
 
 		else
 
 			return FALSE;
 
 	}
 
 }
 
 
 
 
 
 //////////////////////////////////////////////////////////////////////////
 
 //删除指定目录下的所有文件和子目录
 
 void RecursiveDelete(CString szPath)
 
 {
 
 	CFileFind fileFind;
 
 	CString strPath=szPath;
 
 	//说明要查找此目录下的所有文件
 
 	if(strPath.Right(1)!="\\")
 
 		strPath+="\\";
 
 	strPath+="*.*";
 
 	BOOL bRet;
 
 	if (fileFind.FindFile(strPath))
 
 	{
 
 		do 
 
 		{
 
 			bRet=fileFind.FindNextFile();
 
 			if(fileFind.IsDots())//目录为"." 或者是".."?
 
 				continue;
 
 			strPath=fileFind.GetFilePath();
 
 			if (!fileFind.IsDirectory())
 
 			{
 
 				//删除此文件
 
 				::SetFileAttributes(strPath,FILE_ATTRIBUTE_NORMAL);
 
 				::DeleteFile(strPath);
 
 			}
 
 			else
 
 			{
 
 				//递归调用
 
 				RecursiveDelete(strPath);
 
 				//删除此目录
 
 				::SetFileAttributes(strPath,FILE_ATTRIBUTE_NORMAL);
 
 				::RemoveDirectory(strPath);
 
 			}
 
 		} while (bRet);
 
 	}
 
 }
 
 
 
 //////////////////////////////////////////////////////////////////////////
 
 //检查文件是不是有效的PE文件
 
 BOOL isPEFile(CString strPath)
 
 {
 
 	//打开检查文件
 
 	HANDLE hFile=::CreateFile(strPath,GENERIC_READ,
 
 		FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
 
 	if(hFile==INVALID_HANDLE_VALUE)
 
 		AfxMessageBox("无效文件!");
 
 	//定义PE文件中的DOS头和NT头
 
 	IMAGE_DOS_HEADER dosHeader;
 
 	IMAGE_NT_HEADERS ntHeader;
 
 	//验证过程
 
 	BOOL bValid=FALSE;
 
 	DWORD dwRead;
 
 	//读取DOS头
 
 	::ReadFile(hFile,&dosHeader,sizeof(dosHeader),&dwRead,NULL);
 
 	if (dwRead==sizeof(dosHeader))
 
 	{
 
 		if (dosHeader.e_magic==IMAGE_DOS_SIGNATURE)
 
 		{
 
 			//定义NT头
 
 			if (::SetFilePointer(hFile,dosHeader.e_lfanew,NULL,FILE_BEGIN))
 
 			{
 
 				//读取NT头
 
 				ReadFile(hFile,&ntHeader,sizeof(ntHeader),&dwRead,NULL);
 
 				if (dwRead==sizeof(ntHeader))
 
 				{
 
 					if(ntHeader.Signature==IMAGE_NT_SIGNATURE)
 
 						bValid=TRUE;
 
 				}
 
 			}
 
 		}
 
 	}
 
 	return bValid;
 
 }

原文地址:https://www.cnblogs.com/owenyang/p/3579113.html