- 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 ).
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.)
#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?
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.