How to write a program in C++ such that it will delete itself after execution ?
Here is the code in C which will delete the executable after execution.
#include <Windows.h>
#include <strsafe.h>
#define SELF_REMOVE_STRING TEXT("cmd.exe /C ping 1.1.1.1 -n 1 -w 3000 > Nul & Del /f /q \"%s\"")
void DelMe()
{
TCHAR szModuleName[MAX_PATH];
TCHAR szCmd[2 * MAX_PATH];
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
GetModuleFileName(NULL, szModuleName, MAX_PATH);
StringCbPrintf(szCmd, 2 * MAX_PATH, SELF_REMOVE_STRING, szModuleName);
CreateProcess(NULL, szCmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
void main()
{
/* Do what you need */
/* Call this function at the very end of your program to delete itself */
DelMe();
}
std::remove(argv[0])
before return in main can do it.
Some Methods
You could also, use some kind of Scheduled Task...
For Windows try this. It is basically launching a .bat file that loops until the destruction is sucessful:
http://www.codeproject.com/Articles/4027/Writing-a-self-destructing-exe-file
However there is a way to delete the file by itself after execution because every Uninstaller unistalls the software which was installed by it & also deletes the last remaining file i.e., itself such that no files will be remaining in our Hard Disk except some Registry Entries irrespective of the platform it has been installed.
On Unix, just call unlink(2) on the executable.
On Windows, you need a second process to help you. The response from st0le seems to be for unlinking a DLL, but for an executable, you would need to start a second process or use an existing process, and then terminate your executable and have the second process do the deletion.
A very simple approach would be to use cmd.exe to help.
An speculative approach that uses any other process could be to allocate some memory in another process and put the filename you want to delete there, then use CreateRemoteThread() to create a suspended thread in the remote process with an entry point of DeleteFile with an argument of a pointer to the memory you allocated. Then exit your process, the thread suspend count should decrement and then DeleteFile should be called to delete your file.
Issues: Memory leak in the remote process, messy.
An easier way might just be to have a supporting DLL using the techniques from st0le's answer.