C ++ argv路径说明符

时间:2010-04-09 17:50:31

标签: c++ string path argv

在我的编程语言的解释器中,我必须在调用import函数时正确处理这些部分。然后我需要检查这样的文件是否在/libs文件夹中(与我的可执行文件位于同一个地方!)如果它不存在,我必须检查当前脚本的目录。

  • 如何从argv?
  • 获取可执行文件所在目录的确切路径
  • 从路径末尾删除文件的最佳方法是什么,例如:

    C:/a/b/c/file.exe应该成为C:/a/b/c/

6 个答案:

答案 0 :(得分:2)

  1. 没有保证可以做到这一点。您可以尝试查看argv[0],但是它是否具有完整路径或仅仅是二进制文件的名称取决于平台以及如何调用您的流程。
  2. 您可以使用strrchr查找最后一个斜杠,并使用'\0'
  3. 替换其后的字符

    代码示例:

    // Duplicate the string so as not to trash the original
    // You can skip this if you don't mind modifying the original data
    // and the originald is writeable (i.e. no literal strings)
    char *path = strdup(...);
    
    char *last_slash = strrchr(path, '/');
    if (last_slash)
    {
    #if PRESERVE_LAST_SLASH
        *(last_slash + 1) = '\0';
    #else
        *last_slash = '\0';
    #endif
    }
    

答案 1 :(得分:2)

如果argv [0]不包含整个路径,那么Linux(以及其他* nix)上的非可移植方式将在/ proc / self / exe上使用readlink。

答案 2 :(得分:1)

如果您的环境在环境中具有等效的PWD,您只需将/ $ argv [0]附加到其中即可。

这可能会给你一些你不希望的东西,比如/foo1/foo2/../foo3/,但没关系。它是一个有效的路径,可以全局化。

答案 3 :(得分:0)

从字符串末尾向后扫描第一个'/'字符。

答案 4 :(得分:0)

不是最佳,但工作正常:

int main(int argc, char **argv) {
    using namespace std;
    char buffer[MAXPATHLEN];
    realpath(argv[0], buffer);
    string fullpath = buffer;
    fullpath = string(fullpath, 0, fullpath.rfind("/"));
    cout << fullpath << endl;
}

对于相对路径,我使用的是realpath(),它是unix / linux特有的。对于Windows,你可以使用GetModuleFileName(NULL,buffer,MAXPATHLEN),当然分隔符也不一样。

答案 5 :(得分:0)

对于Windows(非可移植),使用:: GetModuleFileName()和:: PathRemoveFileSpec():

TCHAR sPath[MAX_PATH] = {0};
if(::GetModuleFileName(NULL, sPath, MAX_PATH))
    ::PathRemoveFileSpec(sPath))
// sPath is the executable path if the module is an exe