I have an application running on the Windows platform. In one of my methods I need to capture the directory where the application is running, what is the correct way to do it?
I have an application running on the Windows platform. In one of my methods I need to capture the directory where the application is running, what is the correct way to do it?
You may be capturing the directory using _getcwd . You can store it in a variable and call it as soon as you need it. getcwd is a POSIX function that is compiled by all POSIX-compatible platforms. you will only need to include the Unist.d headers in UNIX and direct.h in Windows
An Example:
#include <stdio.h>
#ifdef WINDOWS
#include <direct.h>
#define Define_CurrentDir _getcwd
#else
#include <unistd.h>
#define Define_CurrentDir getcwd
#endif
char LOCAL_DIR[FILENAME_MAX];
if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR)))
{
return errno;
}
std::cout << "Diretorio: " << LOCAL_DIR;
For the Windows system you can use the GetModuleFileName()
function by going to the hModule
is a null value. Something like this (not tested):
#include <iostream>
#include <Windows.h>
using namespace std;
int main ()
{ wchar_t buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH) ;
std::cout << buffer << std::endl;
cin.get();
}
Other operating systems:
_NSGetExecutablePath()
readlink /proc/self/exe
getexecname()
procfs
you can use readlink /proc/curproc/file
- FreeBSD does not have procfs
by default. Another way is to use the getprogname()
function in conjunction with another function, realpath()
.