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

后端 未结 23 1981
温柔的废话
温柔的废话 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:00

    For relative paths, here's what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:

    Say you have a path like this:

    "path/to/file/folder"
    

    For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!

    As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:

    "./path/to/file/folder"
    

    Just adding "./" should get you sorted! :) Then you can start loading from whatever directory you wish, so long as it is with the executable itself.

    EDIT: This won't work if you try to launch the executable from code::blocks if that's the development environment being used, as for some reason, code::blocks doesn't load stuff right... :D

    EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):

    "resources/Example.data"
    

    If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that. Keep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)

提交回复
热议问题