2

The following answer gives a solution using C#, I was wondering what the equivalent would be if one were using only c++ (not c++\cli)

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

Is there anything in boost that might do the trick?

Based on this problem I've been having: Correctly creating and running a win32 service with file I/O

Community
  • 1
  • 1
Rikardo Koder
  • 672
  • 9
  • 16

3 Answers3

8

SetCurrentDirectory (in Win32):

http://msdn.microsoft.com/en-us/library/windows/desktop/aa365530%28v=vs.85%29.aspx

current_path in boost::filesystem:

http://www.boost.org/doc/libs/1_51_0/libs/filesystem/doc/reference.html#current_path

The equivalent for BaseDirectory might be GetModuleFileName (with a null handle for the first argument), followed by GetFullPathName to get the directory from the executable path.

eq-
  • 9,986
  • 36
  • 38
  • 1
    great answer! but is there an equivelent for the "System.AppDomain.CurrentDomain.BaseDirectory" call? i believe it's the path to the exe being run – Rikardo Koder Sep 03 '12 at 21:46
  • Just as an extra, the POSIX API : `#include chdir(const char*)`, which shall work on Linux, Mac, BSDs, ... I heard that Windows also implements some POSIX calls. Can some WinApi expert say something about? – André Oriani Sep 03 '12 at 21:48
  • Hmmm... I believe @Anon ymous answered my question. – André Oriani Sep 03 '12 at 21:50
  • Regarding full path to file name, one of the most abused API's in Windows: GetModuleFileName(), will probably get what you want. I'm not familiar with boost (and I think I'm the last C++ engineer in modern times that isn't) but I'm sure there is a property or API buried in there to do it. – WhozCraig Sep 03 '12 at 21:52
4

Use SetCurrentDirectory WINAPI.

There is one more answer available at What is the difference between _chdir and SetCurrentDirectory in windows?

Perhaps there is a need for Module Name as well(Seems from comments),Here is one from my old store:-

int main()
{
  char path[MAX_PATH]={0};
  GetModuleFileName(0,path,MAX_PATH);
}
Community
  • 1
  • 1
perilbrain
  • 7,961
  • 2
  • 27
  • 35
4

In Windows, the complete equivalent of

System.IO.Directory.SetCurrentDirectory ( System.AppDomain.CurrentDomain.BaseDirectory )` 

would be:

// Get full executable path
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);

// Get executable directory
boost::filesystem::path path(buffer);
path = path.parent_path();

// Set current path to that directory
boost::filesystem::current_path( path );

Note that there is no platform-agnostic way to get an application's directory, as C++ doesn't recognize the concept of directories in the standard. Boost doesn't appear to have an equivalent function either.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180