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

后端 未结 23 1964
温柔的废话
温柔的废话 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 04:59

    Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.

    For example:

    #include 
    #include 
    #include 
    
    int main(int argc, char **argv) {
        char the_path[256];
    
        getcwd(the_path, 255);
        strcat(the_path, "/");
        strcat(the_path, argv[0]);
    
        printf("%s\n", the_path);
    
        return 0;
    }
    

    When run, it outputs:

    jeremy@jeremy-desktop:~/Desktop$ ./test
    /home/jeremy/Desktop/./test

提交回复
热议问题