Get path of executable

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

    in Unix(including Linux) try 'which', in Windows try 'where'.

    #include 
    
    #define _UNIX
    
    int main(int argc, char** argv)
    {
            char cmd[128];
            char buf[128];
            FILE* fp = NULL;
    #if defined(_UNIX)
            sprintf(cmd, "which %s > my.path", argv[0]);
    #else
            sprintf(cmd, "where %s > my.path", argv[0]);
    #endif
            system(cmd);
            fp = fopen("my.path", "r");
            fgets(buf, sizeof(buf), fp);
            fclose(fp);
    
            printf("full path: %s\n", buf);
            unlink("my.path");
    
            return 0;
    }
    

提交回复
热议问题