简体   繁体   中英

C++: Best way to get exe folder path?

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?

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);
    }
}

EDIT: Best way being a cross platform command (if it doesn't exist then use Windows) that gives the folder directory directly.

I doubt there is anything better than the standard library.

#include <filesystem>

std::filesystem::path cp = std::filesystem::current_path();

Ref: https://en.cppreference.com/w/cpp/filesystem

e2a: Excerpt from the ref link.

Notes

The current working directory is the directory, associated with the process, that is used as the starting location in pathname resolution for relative paths.

The current path as returned by many operating systems is a dangerous global variable. It may be changed unexpectedly by third-party or system library functions, or by another thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM