[英]How to specify the directory of a .config file in C++ code?
I have a C++ program that I built using Visual Stuidos. 我有一个使用Visual Stuidos构建的C ++程序。 It has to read some variables from a .config file.
它必须从.config文件中读取一些变量。 I notice that when I run the program from VS (ie I open the VS solution and press the "Start Without Debugging" button), it can't find the .config file unless it's in the "release" or "debug" directory.
我注意到当我从VS运行程序时(即我打开VS解决方案并按下“Start Without Debugging”按钮),它找不到.config文件,除非它在“release”或“debug”目录中。 However, I'd like to be able to run the program from the VS solution, while keeping the .config file in the same directory as the .sln file.
但是,我希望能够从VS解决方案运行该程序,同时将.config文件保存在与.sln文件相同的目录中。 Is there a way I can set the path of the .config file to this directory, perhaps somewhere in the source code?
有没有办法可以将.config文件的路径设置到这个目录,也许在源代码的某个地方?
Thanks. 谢谢。
I would take advantage of Visual Studios directory macros and set an additional include path in your solution directory, I answered a question previously on this site relating to include directories, so here is a diagram I created: 我会利用Visual Studios目录宏并在解决方案目录中设置一个额外的包含路径,我之前在这个网站上回答了一个与包含目录有关的问题 ,所以这是我创建的图表:
Don't pay attention to the text on the left side, but the black text on the right side is what you're looking for. 不要注意左侧的文字,但右侧的黑色文字是您正在寻找的。
$(SolutionDir)
is a macro that finds the directory of your solution, and adding this will allow your program to have access to this directory during the program. $(SolutionDir)
是一个查找解决方案目录的宏,添加它可以让程序在程序中访问该目录。
You can call GetModuleFileName to get the full path to your exe file. 您可以调用GetModuleFileName来获取exe文件的完整路径。 From there you can remove the lowest level (/debug or /release) to get the project path.
从那里,您可以删除最低级别(/ debug或/ release)以获取项目路径。
That should get you what you asked for, but what you asked for is not a good approach. 那应该可以得到你所要求的,但你要求的并不是一个好方法。 Putting your config file in your exe directory will encounter problems later on with non-admin user rights.
将配置文件放在exe目录中将在以后使用非管理员用户权限时遇到问题。 The recommended place for such files can be found by calling SHGetFolderPath, where you can create an accessible folder for your app.
可以通过调用SHGetFolderPath找到此类文件的推荐位置,您可以在其中为应用程序创建可访问的文件夹。
Just set Project Properties|Debugging|Working Directory
to $(SolutionDir). 只需将
Project Properties|Debugging|Working Directory
为$(SolutionDir)即可。 Or any directory you want. 或者您想要的任何目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.