Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get exe folder path?

Tags:

c++

I found this in another forum that is supposed to give it to you. But I think this may not be the best way, also I think it results in a memory leak due to the array not being deleted. Is this true?

Also is this the best way? Best way being a cross platform command (if it doesn't exist then use Windows) that gives the folder directory directly.

std::string ExePath() 
{
    using namespace std;

    char buffer[MAX_PATH];

    GetModuleFileName(NULL, buffer, MAX_PATH);

    string::size_type pos = string(buffer).find_last_of("\\/");

    if (pos == string::npos)
    {
        return "";
    }
    else 
    {
        return string(buffer).substr(0, pos);
    }
}
like image 898
Yiannis128 Avatar asked Jun 16 '18 16:06

Yiannis128


1 Answers

There is no memory leak in your code, but there are some issues with it:

  • it is Windows-specific,
  • it works with local code-page and does not support arbitrary Unicode files names.

Unfortunately, there is no standard way of accomplishing this task just with C++ library, but here is a code that will work on Windows and Linux, and support Unicode paths as well. Also it utilizes std::filesystem library from C++17:

#include <filesystem>
#ifdef _WIN32
#include <windows.h>
#elif
#include <unistd.h>
#endif

std::filesystem::path GetExeDirectory()
{
#ifdef _WIN32
    // Windows specific
    wchar_t szPath[MAX_PATH];
    GetModuleFileNameW( NULL, szPath, MAX_PATH );
#else
    // Linux specific
    char szPath[PATH_MAX];
    ssize_t count = readlink( "/proc/self/exe", szPath, PATH_MAX );
    if( count < 0 || count >= PATH_MAX )
        return {}; // some error
    szPath[count] = '\0';
#endif
    return std::filesystem::path{ szPath }.parent_path() / ""; // to finish the folder path with (back)slash
}
like image 127
Fedor Avatar answered Nov 13 '22 01:11

Fedor