How do I get the directory that a program is running from?

后端 未结 23 1670
温柔的废话
温柔的废话 2020-11-22 04:39

Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the

23条回答
  •  长发绾君心
    2020-11-22 05:12

    This is from the cplusplus forum

    On windows:

    #include 
    #include 
    
    std::string getexepath()
    {
      char result[ MAX_PATH ];
      return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
    }
    

    On Linux:

    #include 
    #include 
    #include 
    
    std::string getexepath()
    {
      char result[ PATH_MAX ];
      ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
      return std::string( result, (count > 0) ? count : 0 );
    }
    

    On HP-UX:

    #include 
    #include 
    #define _PSTAT64
    #include 
    #include 
    #include 
    
    std::string getexepath()
    {
      char result[ PATH_MAX ];
      struct pst_status ps;
    
      if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)
        return std::string();
    
      if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)
        return std::string();
    
      return std::string( result );
    }
    

提交回复
热议问题