Get path of executable

前端 未结 23 2091
清歌不尽
清歌不尽 2020-11-22 07:04

I know this question has been asked before but I still haven\'t seen a satisfactory answer, or a definitive \"no, this cannot be done\", so I\'ll ask again!

All I wa

23条回答
  •  半阙折子戏
    2020-11-22 07:51

    Using args[0] and looking for '/' (or '\\'):

    #include 
    #include  // to show the result
    
    int main( int numArgs, char *args[])
    {
        // Get the last position of '/'
        std::string aux(args[0]);
    
        // get '/' or '\\' depending on unix/mac or windows.
    #if defined(_WIN32) || defined(WIN32)
        int pos = aux.rfind('\\');
    #else
        int pos = aux.rfind('/');
    #endif
    
        // Get the path and the name
        std::string path = aux.substr(0,pos+1);
        std::string name = aux.substr(pos+1);
        // show results
        std::cout << "Path: " << path << std::endl;
        std::cout << "Name: " << name << std::endl;
    }
    

    EDITED: If '/' does not exist, pos==-1 so the result is correct.

提交回复
热议问题