Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a program in C++ such that it will delete itself after execution?

Tags:

c++

How to write a program in C++ such that it will delete itself after execution ?

like image 544
Saulius Avatar asked Aug 11 '10 09:08

Saulius


People also ask

How do you write a program such that it will delete itself after execution?

Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed. Explanation: This can be done using the remove function in C.

Can an executable delete itself?

Can an EXE delete itself? If the program or the EXE is not running, it will be able to delete itself. Security software usually terminates these programs and quarantines them. However, when the program is in memory of the OS, it will not able to delete itself.

How do you delete a file in C++?

The remove() function in C++ deletes a specified file. It is defined in the cstdio header file.


1 Answers

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(); } 
like image 104
gtikok Avatar answered Sep 22 '22 12:09

gtikok