c++windowsmfcvisual-c++-2013

How to set a directory for a executable file for different Operating Systems?


I am trying to set a specific directory for my code which is a MFC project. A code for a dialog has been written(in visual studio c++) and now I am going to use .exe file of this code in different OS, and replace this file in those directory that I want. To arrive at this goal, I used GetModuleFileName function.Therefore, by following these suggestions I included this piece of code to OnInitDialog() function of my code:

//function that gets the directory without the file name:
    TCHAR szFilePath[_MAX_PATH];
    TCHAR driveLetter[3];      
    TCHAR directory[MAX_PATH];  
    TCHAR FinalPath[MAX_PATH];
    ::GetModuleFileName(NULL, szFilePath, _MAX_PATH);//Retrieves the current directory for the current process.
    // Add all the files and directories in the windows directory.
    //VERIFY(0 < ::GetWindowsDirectory(lpszWinPath, MAX_PATH));

    // Make the windows directory the current directory.
    ::GetCurrentDirectory(MAX_PATH, lpszOldPath);
    //::SetCurrentDirectory(lpszWinPath);
    ::SetCurrentDirectory("C:\\Program Files");

However, now I don't get any error message but I don't know why I can't see any output. As an example I expect a .exe file in specified directory be created.


Solution

  • The code above doesn't create any files whatsoever, so it won't create an EXE file. Assuming that it tried to create .\Foo.EXE it would effectively create C:\Program Files\Foo.EXE. This is not correct for a number of reasons. For starters, don't hardcode the path, as it differs from system to system. Call SHGetKnownFolderPath(FOLDERID_ProgramFiles, ...) to get that path.

    Next, create a subdirectory there. Don't put executables there directly.

    Finally, and perhaps most importantly, realize that this is the task of an installer running elevated. In normal use, Program Files is read-only. then normal programs don't create executables either.