是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
当前回答
#include <windows.h>
using namespace std;
// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
const unsigned long maxDir = 260;
char currentDir[maxDir];
GetCurrentDirectory(maxDir, currentDir);
return string(currentDir);
}
其他回答
你不能为此目的使用argv[0],通常它包含可执行文件的完整路径,但也不是必须的——进程可以在字段中使用任意值创建。
还要注意,当前目录和可执行文件所在的目录是两个不同的东西,所以getcwd()也帮不了你。
Windows上使用GetModuleFileName(), Linux上读取/dev/proc/procID/..文件。
这是来自cplusplus论坛
在windows上:
#include <string>
#include <windows.h>
std::string getexepath()
{
char result[ MAX_PATH ];
return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
}
在Linux上:
#include <string>
#include <limits.h>
#include <unistd.h>
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 );
}
在hp - ux上:
#include <string>
#include <limits.h>
#define _PSTAT64
#include <sys/pstat.h>
#include <sys/types.h>
#include <unistd.h>
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 );
}
对于控制台的Windows系统,可以使用system(dir)命令。控制台提供目录等信息。在cmd下阅读有关dir命令的信息。但是对于类unix系统,我不知道…如果执行了该命令,请读取bash命令。Ls不显示目录…
例子:
int main()
{
system("dir");
system("pause"); //this wait for Enter-key-press;
return 0;
}
在Windows上,最简单的方法是使用stdlib.h中的_get_pgmptr函数来获取一个指向字符串的指针,该字符串表示可执行文件的绝对路径,包括可执行文件的名称。
char* path;
_get_pgmptr(&path);
printf(path); // Example output: C:/Projects/Hello/World.exe
不,没有标准的方法。我相信C/ c++标准甚至没有考虑目录(或其他文件系统组织)的存在。
在Windows上,当hModule参数设置为NULL时,GetModuleFileName()将返回当前进程可执行文件的完整路径。Linux我帮不上忙。
此外,您还应该明确您想要的是当前目录还是程序映像/可执行文件所在的目录。就目前情况来看,你的问题在这一点上有点模棱两可。