tags:

views:

88

answers:

2

I need to access some files with fstream in my C++ app on Windows. Those files are all located in subfolders of the folder where my exe file is located.

  • What is the easiest and more important: safest way to get the path to the folder of the current executable?
+3  A: 

Use GetModuleHandle and GetModuleFileName to find out where your exe is running from.

HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);

Then strip the exe name from path.

sean e
Is there any way to do this without the Win32 API?
asas
@asas: No, not an easy and safe way.
Adrian McCarthy
@asas: Writing a C++ Windows application without using Win32 API? Like using Qt instead?
sean e
sean e: Yes, without the Win32 API. It isn't a GUI app - it's an interpreter I currently write in MSVC which shouldn't be too hard to port - Win32 API makes it hard to port.
asas
@asas: ahh - no experience there. Might want to look at a portable library - maybe apache portable runtime library: http://apr.apache.org/ or the Netscape Portable Runtime: http://www.mozilla.org/projects/nspr/
sean e
A: 

By default, the directory that the exe is run from should be the starting location. So opening a file in a subfolder should be as easy as

fstream infile; 
infile.open(".\\subfolder\\filename.ext");

from within your program.

However, there is no real way to GUARANTEE this will always work unless you either use a framework that wraps the needed features (I'd look at boost), or using the Windows API directly such as GetModuleFileName (as sean e suggested)

KevenK
What? Have your ever heard of *run in*? You don't have to tell me that the path where the exe runs in is the default...
asas
With all due respect, I have no idea what you just tried to say. I'm not sure what you are referencing with *run in*. Also, text on a web page doesn't necessarily share the meanings of your innuendo and ellipses. So please explain what your second sentence is intended to mean.
KevenK
In case you misunderstand: Each process has it's own value representing the current directory. By default, this value should be set to the directory in which the executable file is located. You can check this directory using the API calls for `GetCurrentDirectory()` or set it using `SetCurrentDirectory()`. While I realize this isn't an exact solution to your problem (as I stated in the original text), the information is not wrong http://msdn.microsoft.com/en-us/library/aa363806.aspx. If you felt that's worth a down-vote, I'm not sure you understand the intended use of the voting system here.
KevenK
@KevenK: He is probably referring to the "Start in" option where you can specify the starting working directory in a Windows Start menu program link.
sean e