使用某个程序打开文件会更改该程序的工作目录吗?
我的桌面上保存了一个文件,当我用程序打开它时,工作目录会更改为桌面,这意味着我的程序在工作目录中搜索这些文件时无法加载它所需的某些文件。有没有办法阻止工作目录像这样改变?
I have a file saved to my desktop, when I open it with my program the working directory changes to the desktop, this means my program can not load in some files it needs as it searches for these in the working directory. Is there a way I can stop the working directory from changing like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以设置一个标记来避免当前目录发生更改,称为 OFN_NOCHANGEDIR
http://msdn.microsoft.com/en-us/library/ms646839(v=vs.85).aspx
There's a flag you can set to avoid the current directory from changing called OFN_NOCHANGEDIR
http://msdn.microsoft.com/en-us/library/ms646839(v=vs.85).aspx
您可以在启动时保存工作目录并使用绝对路径。事实上,最好始终使用绝对路径打开文件,除非您确实想依赖当前工作目录。
You can just save your working directory at startup and use absolute paths. In fact, it's better to always open files with absolute paths, unless you really want to rely on the current working directory.
您最好确定进程位置,然后将其用作在哪里查找其他文件的关键?启动程序的方式有很多种,这会影响工作目录。
请参阅:此处的答案关于如何获取进程位置并删除可执行文件名的良好描述(查看注释)
本质上,您可以使用:
GetModuleFileName
或GetModuleFileNameEx
。进而:
PathRemoveFileSpec
删除文件名You would be better off determining the processes location, then using it as the key for where to find the other files? There are many ways that programs can be launched, which effect the working directory.
See: The answer here for a good description of how to get the processes location and strip out the executable filename (look in the comments)
Essentially, you use:
GetModuleFileName
orGetModuleFileNameEx
.and then:
PathRemoveFileSpec
to remove the file name打开文件不会更改当前目录。也许您使用通用的打开文件对话框? 这里一篇文章将解释有关如何更改您当前的目录。
Opening a file doesn't change your current directory. Perhaps you using the common open file dialog? Here is an article that will explain all about how that changes your current directory.
使用
SetCurrentDirectory
来做到这一点。您可以使用
GetModuleFileName
找到可执行文件use
SetCurrentDirectory
to do that.You can locate the executable by using
GetModuleFileName