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.
In Visual Studio 2010:
- Go to the project properties (rigth click on the project name in the Solution Explorer, then Properties on the pop up menu).
- Then, under Configuration Properties / Debugging, set Working Directory to
$(SolutionDir)$(Configuration)\
.
Full list of available macros (on learn.microsoft.com) : Common macros for MSBuild commands and properties
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).
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.
If your current directory is changing, you should probably save your working directory at startup in some variable you can access later to set cwd back there. At least this is how I understand your question.
For getting the cwd, this might help.
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.
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);
}
精彩评论