Regarding Folder of Execution

- This question is currently only for windows; but I would like to know about a cross-platform way to perform what I want to do (explained below) -

I have created a little program:

1
2
3
4
5
6
7
8
9
#include <iostream>

int main(int argc, char *argv[])
{
    for (int i = 0; i < argc; ++i)
    {
        std::cout << argv[i] << '\n';
    }
}


I have added this program to the windows PATH. I put this program in C:\Program Files\Program\

I now navigate to C:\Data\VariousTexts\ using CMD.

Then I type in: "program x"

The program will print out "program\nx" as by default. What I would like to get hold of is the folder in which the program is actually being called.
( I want to somehow get "C:\Data\VariousTexts\" to be read into my program ).

How do I perform such an operation?
Last edited on
Why do you need it? Just use relative paths with "./file-in-current-directory.txt".

If you need an absolute path to the working directory, use boost filesystem.
Last edited on
Oh; I think I have found the solution using boost:

getcwd = boost::filesystem::path full_path( boost::filesystem::current_path() );

from http://stackoverflow.com/questions/3935874/boostfilesystem-relative-path-and-current-directory


@L B

Because ./x will put the raw ./x string as an argument, and not replace ./ by the entire directory structure that comes before x (on my system anyway.)
On Windows... with narrow strings, this is done with the GetModeulFileNameA function:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx


Example usage:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <windows.h>

int main()
{
    char filename[MAX_PATH];

    ::GetModuleFileNameA( NULL, filename, MAX_PATH );
    filename[MAX_PATH-1] = 0;  // prevent possible overflow on WinXP

    std::cout << filename;
}




Of course... this is Windows-only (not portable). Some widgetry libs probably have this functionality in a portable way (I know wxWidgets does... Qt might also but I'm not sure). But those are very big libs to add just for something so minor.



EDIT:

L B's suggestion will also work for most cases... although the working directory and the executable directory are not always the same. My approach gets you the executable directory.


EDIT AGAIN:

Ninja'd But again that example expands the working directory, not the executable directory. Which one do you really want?
Last edited on
As I have stated in my question; I would like the working directory; the directory that the executable needs to work with. I think I have a good answer from boost tho; and that is no problem since I am already using boost in my project.
Ah okay. I misread, sorry. That boost solution is the best way to go then. =)
Last edited on
Topic archived. No new replies allowed.