文件自我删除是一个很有必要的功能,尤其在国家之间的网络战争。
#include "stdafx.h" #include <sys/stat.h> //加入状态显示头文件. BOOL SelfDel1() { SHELLEXECUTEINFO sei; TCHAR szModule [MAX_PATH],szComspec[MAX_PATH],szParams [MAX_PATH]; // 获得文件名. if((GetModuleFileName(0,szModule,MAX_PATH)!=0) && (GetShortPathName(szModule,szModule,MAX_PATH)!=0) && (GetEnvironmentVariable("COMSPEC",szComspec,MAX_PATH)!=0)) { // 设置命令参数. lstrcpy(szParams,"/c del "); lstrcat(szParams, szModule); lstrcat(szParams, " > nul"); // 设置结构成员. sei.cbSize = sizeof(sei); sei.hwnd = 0; sei.lpVerb = "Open"; sei.lpFile = szComspec; sei.lpParameters = szParams; sei.lpDirectory = 0; sei.nShow = SW_HIDE; sei.fMask = SEE_MASK_NOCLOSEPROCESS; // 执行shell命令. if(ShellExecuteEx(&sei)) { // 设置命令行进程的执行级别为空闲执行,使本程序有足够的时间从内存中退出. SetPriorityClass(sei.hProcess,IDLE_PRIORITY_CLASS); SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); // 通知Windows资源浏览器,本程序文件已经被删除. SHChangeNotify(SHCNE_DELETE,SHCNF_PATH,szModule,0); return TRUE; } } return FALSE; } BOOL SelfDel2() { CStdioFile file; CFileException fileEx; TCHAR szDir[MAX_PATH]; TCHAR szModule[MAX_PATH]; GetModuleFileName(0, szModule, sizeof(szModule)); // 获得应用程序名. GetCurrentDirectory(MAX_PATH, szDir); // 获得文件的当前目录. CString strFilePath=CString(szDir)+"tempDel.bat"; // 临时批处理文件名. if(!file.Open(strFilePath,CFile::modeWrite | CFile::typeText | CFile::modeCreate,&fileEx)) { #ifdef _DEBUG afxDump << "The file could not be opened " << strFilePath<<"\n"; afxDump << "Cause :"<<fileEx.m_cause << "\n"; #endif return FALSE; } CString strCmdLine1,strCmdLine2; strCmdLine1.Format("del %s\n",szModule); strCmdLine2.Format("del %%0\n"); file.WriteString(strCmdLine1); // 写删除EXE的命令行. file.WriteString(strCmdLine2); // 写删除BAT的命令行. file.Close(); WinExec(strFilePath,SW_HIDE); // 执行自行删除操作. return TRUE; } void main() { SelfDel1(); }