Wednesday, 21 August 2013

Delete Itseft In C++

It  cleans up  itself  .
bool DeleteItself(string PathName , string FileName)
{
 char *pathResult= (char *)malloc( 256*( sizeof(char)) );
 if(pathResult == NULL)
 {
   return false;
 }
 sprintf(pathResult, "%s%s", PathName.c_str(),"\\Uninstall.bat");
 FILE* log;
 errno_t err  = fopen_s(&log ,pathResult, "a+");
 if (err != 0)
 {
  return FALSE;
 }
 fprintf(log, "%s%s%s%s\n","DEL ",PathName.c_str(),"\\",FileName.c_str());
 fprintf(log, "%s%s%s%s\n","DEl ",PathName.c_str(),"\\","Uninstall.bat");
 fclose(log);

 ShellExecuteA(NULL,
            "open",
            pathResult,
            NULL,
            NULL,
            SW_HIDE);

 if(pathResult)
 {
  free(pathResult);
  pathResult =0;
 }
 return TRUE;

}

int main()
{
 cout<<"hello world"<<endl; 
     //.......code....................
 DeleteItself("C:\\.....\\Release", "Test.exe");
 return 1;
}
//=======================================================================

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>     /* malloc, free, rand */
#include <iostream>
#include <string>
using std::string;
using namespace  std;

bool DeleteItself()
{
 string PathName ;
 string FileName ;
 char buffer[MAX_PATH];
 GetModuleFileNameA( NULL, buffer, MAX_PATH );
 string::size_type pos = string( buffer ).find_last_of( "\\/" );
 PathName = string( buffer ).substr( 0, pos);
    FileName = string( buffer ).substr( pos+1, string( buffer ).length() - pos);
 
 char *pathResult= (char *)malloc( 256*( sizeof(char)) );
 if(pathResult == NULL)
 {
   return false;
 }
 sprintf(pathResult, "%s%s", PathName.c_str(),"\\Uninstall.bat");
 FILE* log;
 errno_t err  = fopen_s(&log ,pathResult, "a+");
 if (err != 0)
 {
  return FALSE;
 }
 fprintf(log, "%s%s%s%s\n","DEL ",PathName.c_str(),"\\",FileName.c_str());
 fprintf(log, "%s%s%s%s\n","DEl ",PathName.c_str(),"\\","Uninstall.bat");
 fclose(log);

 ShellExecuteA(NULL,
            "open",
            pathResult,
            NULL,
            NULL,
            SW_HIDE);

 if(pathResult)
 {
  free(pathResult);
  pathResult =0;
 }
 return TRUE;

}

int main()
{
 cout<<"hello world"<<endl; 
     //.......code....................
 DeleteItself();
 return 1;
}

ww.cplusplus.com/forum/windows/105447/
http://www.catch22.net/tuts/self-deleting-executables
http://www.howtodothings.com/computers/a1402-delete-a-running-exe.html
http://ethioprogrammer.blogspot.com/2012/04/delete-itself-after-execution-c-and.html

No comments:

Post a Comment