Reputation: 6239
I want to set the current directory to the solution directory/configuration name. How do I do that? Can I use the global variables somehow?
I am trying to read a file and the current directory changes in the middle of the code. I want to change it back.
Upvotes: 26
Views: 101748
Reputation: 165
Using GetCurrentDirectory
to have a full path and roll back to where you want to stay with standard C++ string API. Here is my sample code for your reference.
int main() {
TCHAR current_dir_wc[MAIN_FN_LEN_LIMIT];
char current_dir[MAIN_FN_LEN_LIMIT];
char project_dir[MAIN_FN_LEN_LIMIT];
GetCurrentDirectory(MAIN_FN_LEN_LIMIT, current_dir_wc);
sprintf(current_dir, "%s\\", wc2str(current_dir_wc).c_str());
strncpy(project_dir, (const char*)current_dir, (strstr((const char*)current_dir, "UR_VS_SOLUTION_NAME")-current_dir+strlen("UR_VS_SOLUTION_NAME\\")));
printf("[%s]Current DIR:%s\n", __func__, current_dir);
printf("[%s]Project DIR:%s\n", __func__, project_dir);
}
Upvotes: 0
Reputation: 2165
For Visual Studio purposes (include header, etc) you can use macro like $(ProjectDir) or $(SolutionDir) listed here: VS macro list
To read files in code of your app use Windows API function GetCurrentDirectory that retrieves path to your process directory. Compiled code may live independently of project therefore it make sense to refer path to data files relatively to process (exe).
It seems author of question asks about 2-nd item and others answer to 1-st item.
Upvotes: 1
Reputation: 6210
Have you tried using the environment variable $(SolutionDir)
?
With reference to this thread here.
Also, hopefully, the version of VS does not matter, but this answer is furnished based on the assumption that the platform is VS2005.
Upvotes: 5
Reputation: 8064
In Visual Studio 2010:
$(SolutionDir)$(Configuration)\
.Full list of available macros (on learn.microsoft.com) : Common macros for MSBuild commands and properties
Upvotes: 59
Reputation: 12901
You can use the posix subsystem ( <direct.h>
) and access the functions
_getcwd()/_wgetcwd()
Gets the current working directory
_chdir()/_wchdir()
Sets the current working directory
If you need your code to be cross platform, you can do the following:
#ifdef _WIN32
# include <direct.h>
# define getcwd _getcwd
# define chdir _chrdir
#else
# include <unistd.h>
#endif
and use getcwd
and chdir
(w/o the leading underscore).
Upvotes: 6