Get path of executable

前端 未结 23 1525
清歌不尽
清歌不尽 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:35

    This way uses boost + argv. You mentioned this may not be cross platform because it may or may not include the executable name. Well the following code should work around that.

    #include 
    
    #include 
    
    #include 
    
    namespace fs = boost::filesystem;
    
    
    int main(int argc,char** argv)
    {
        fs::path full_path( fs::initial_path() );
    
        full_path = fs::system_complete( fs::path( argv[0] ) );
    
        std::cout << full_path << std::endl;
    
        //Without file name
        std::cout << full_path.stem() << std::endl;
        //std::cout << fs::basename(full_path) << std::endl;
    
        return 0;
    }
    

    The following code gets the current working directory which may do what you need

    #include 
    #include 
    
    #include 
    
    namespace fs = boost::filesystem;
    
    
    int main(int argc,char** argv)
    {
        //current working directory
        fs::path full_path( fs::current_path() );
    
        std::cout << full_path << std::endl;
    
        std::cout << full_path.stem() << std::endl;
        //std::cout << fs::basepath(full_path) << std::endl;
    
        return 0;
    }
    

    Note Just realized that basename() was deprecated so had to switch to .stem()

提交回复
热议问题