c++copygetmodulefilename

Copy current executable to another path C++ (Windows only)


I forgot how to program in C++, I want my exutable to copy itself to another path. I found a code that do what I want to do but there are conversion error that I don't know how to resolve :

void Victim::replicate()
{
  char filename[ MAX_PATH ];
  char newLocation[]="C:\\Users\\myUsername\\Desktop\\";
  BOOL stats=0;
  DWORD size = GetModuleFileNameA( NULL, filename, MAX_PATH );
  CopyFile(filename, newLocation, stats);
      
}

I got an error while using the CopyFile function, It expect LPCWSTR type for filename and newLocation But if I declare those variable as LPCWSTR, the GetModuleFileNameA function will not work anymore.


Solution

  • It seems your project is set to use the W versions of the API functions by default. You override that by calling the A (Ansi) version of GetModuleFileName. Don't - or do, but then you also need to call CopyFileA.

    Forcing Ansi version usage:

    void Victim::replicate()
    {
      char filename[ MAX_PATH ];
      char newLocation[] = "C:\\Users\\myUsername\\Desktop\\";
      BOOL stats=0;
      DWORD size = GetModuleFileNameA( NULL, filename, MAX_PATH );
      CopyFileA(filename, newLocation, stats);     
    }
    

    Forcing Wide version usage:

    void Victim::replicate()
    {
      wchar_t filename[ MAX_PATH ];
      wchar_t newLocation[] = L"C:\\Users\\myUsername\\Desktop\\";
      BOOL stats=0;
      DWORD size = GetModuleFileNameW( NULL, filename, MAX_PATH );
      CopyFileW(filename, newLocation, stats);     
    }
    

    Going with the project default:

    void Victim::replicate()
    {
      TCHAR filename[ MAX_PATH ];
      TCHAR newLocation[] = _T("C:\\Users\\myUsername\\Desktop\\");
      BOOL stats=0;
      DWORD size = GetModuleFileName( NULL, filename, MAX_PATH );
      CopyFile(filename, newLocation, stats);     
    }