Rikardo Koder
Rikardo Koder

Reputation: 672

Setting the current directory of a running app in C++

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

Upvotes: 2

Views: 7066

Answers (3)

Drew Dormann
Drew Dormann

Reputation: 63725

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.

Upvotes: 4

eq-
eq-

Reputation: 10096

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.

Upvotes: 8

perilbrain
perilbrain

Reputation: 8187

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);
}

Upvotes: 4

Related Questions