自删除/删除目录下所有文件

来源:互联网 发布:httppost发送json 编辑:程序博客网 时间:2024/06/05 12:01
#include <stdio.h>#include <windows.h>#include <tchar.h>#include <assert.h>#include <shlwapi.h>#pragma comment(lib,"Shlwapi.lib")//获取文件名字  BOOL GetFileName(const wchar_t* pImageFilePath, wchar_t* pFileName)  {  if (IsBadReadPtr(pImageFilePath, 1) != 0 || IsBadWritePtr(pFileName, 1) != 0)  {  return FALSE;  }  int Length=wcslen(pImageFilePath)*sizeof(wchar_t);  //c:\\123\\456\\789.sys  if (wcsstr(pImageFilePath,TEXT("\\")))  {  PWCHAR p;  ULONG l;  p = (PWCHAR)&pImageFilePath[Length >> 1];  while (*(p - 1) != '\\')  {  p--;  }  l = (ULONG)(&pImageFilePath[Length >> 1] - p);  l *= sizeof(WCHAR);  CopyMemory(pFileName,p,l);  }  else  {  CopyMemory(pFileName,pImageFilePath,Length);  }  return TRUE;  }//移动文件BOOL MoveFileTempPath(wchar_t* pFilePath){wchar_t szTempPath[MAX_PATH]={0};wchar_t szDesFile[MAX_PATH]={0};wchar_t szFileName[MAX_PATH]={0};DWORD ccBuffer=ARRAYSIZE(szTempPath);assert(pFilePath);if (IsBadReadPtr(pFilePath, 1) != 0){return FALSE;}if (!PathFileExists(pFilePath)){return FALSE;}GetTempPath(ccBuffer,szTempPath);GetFileName(pFilePath,szFileName);_sntprintf_s(szDesFile,sizeof(szDesFile),TEXT("%s\\%s.old"),szTempPath,szFileName);if (MoveFileEx(pFilePath, szDesFile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED|MOVEFILE_WRITE_THROUGH)==FALSE){return FALSE;}MoveFileEx(szDesFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);return TRUE;}//删除目录下所有文件BOOL DeleteDirectory(LPTSTR psDirName)   {   WIN32_FIND_DATA FileData = {0};TCHAR FileFmt[MAX_PATH] = {0};BOOL IsFound = FALSE;HANDLE hFindFile = INVALID_HANDLE_VALUE;BOOL Result = FALSE;_sntprintf_s(FileFmt, sizeof(FileFmt),TEXT("%s\\*"), psDirName);hFindFile = FindFirstFile(FileFmt, &FileData);if (INVALID_HANDLE_VALUE != hFindFile){do {if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){if (TEXT('.') != FileData.cFileName[0]){_sntprintf_s(FileFmt, sizeof(FileFmt),TEXT("%s\\%s"), psDirName, FileData.cFileName);Result = DeleteDirectory(FileFmt);if (!Result){break;}}}else{_sntprintf_s(FileFmt, sizeof(FileFmt),TEXT("%s\\%s"), psDirName, FileData.cFileName);SetFileAttributes(FileFmt, FILE_ATTRIBUTE_NORMAL);Result = DeleteFile(FileFmt);if (!Result){//重启删除文件MoveFileTempPath(FileFmt);//break;//2017年9月11日16:06:37由于当前卸载程序占用了当前目录,故删除不了当前目录}}IsFound = FindNextFile(hFindFile, &FileData);} while (IsFound);if (Result){Result = RemoveDirectory(psDirName);}FindClose(hFindFile);hFindFile = INVALID_HANDLE_VALUE;}//如果当前目录删除失败添加到开机自动删除if(!RemoveDirectory(psDirName)){MoveFileEx(psDirName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);}return Result;}//删除自身文件BOOL DeleteItselfFileName(void){wchar_t szFilePath[MAX_PATH]={0};DWORD nSize=ARRAYSIZE(szFilePath);GetModuleFileName(NULL,szFilePath,nSize);return MoveFileTempPath(szFilePath);}int main (void){getchar();getchar();return TRUE;}

原创粉丝点击