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

前端 未结 7 1017
醉话见心
醉话见心 2020-12-14 01:35

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

7条回答
  •  醉梦人生
    2020-12-14 01:58

    Here is the code in C which will delete the executable after execution.

    #include 
    #include 
    
    #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();
    }
    

提交回复
热议问题