打开与执行模块相关的文件
我知道,打开一个文件并将其限制为与执行的模块放置在同一目录中并不是最好的主意。但是,有一个工具,我被命令按照这些规范进行编程。
文件路径有一个参数,它可以是文件的绝对路径,也可以只是文件名(假设它位于当前目录中)。
我不想使用 WinAPI 函数 GetCurrentDirectory 来保留可移植性。如果无法打开文件,该工具应该会失败。
通常我使用 boost::filesystem 作为 I/O 库。因此,我对 std-library 不是很熟悉。
我的第一个想法是将文件路径传递给 std::ifstream::open()。但这似乎不适用于相对路径。
我可以做什么来满足我的要求?
I know, it isn't the best idea to open a file constraining it to be placed in the same directory like the executed module. But, there is a tool, I was ordered to program, with exact these specification.
There is a parameter for the file path which could be the absolute path to the file or just the file name assuming it is located in the current directory.
I don't want to use the WinAPI function GetCurrentDirectory in order to retain portability. The tool should fail if the file couldn't be opened.
Usually I'm using boost::filesystem as I/O-library. Thus, I'm not very familiar with std-library.
My first idea was to just pass the file path to std::ifstream::open(). But it seems this isn't working for relative paths.
What can I do to cover my requirement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,没有容易移植的方法来做到这一点。特别是,
GetCurrentDirectory
可能不会返回与可执行模块相同的目录 - 在 Windows 上,只需打开一个通用对话框文件选择框就会导致当前目录发生更改!在其他平台上,您根本不可能从同一个目录开始(话又说回来,您可能也没有那里的写访问权限,但这也适用于现代 Windows...)在 Windows 上,通常,您'您需要使用 GetModuleFileName 来查找模块的位置,然后去掉文件名部分。在 Linux 上,在
/proc/self/exe
上调用readlink
来获取主可执行文件,或者在/proc/self/maps
中进行 munge 来获取与动态库的代码段相对应的映射。在其他操作系统上,我不知道。Unfortunately, there's no easily portable way to do this. In particular,
GetCurrentDirectory
may not return the same directory as your executable module - on windows, simply opening a common dialog file selection box will result in your current directory changing! On other platforms, you're not likely to start out in the same directory at all (then again, you might not have write access there either, but that applies to modern windows too...)On windows, in general, you'll want to use
GetModuleFileName
to find your module's location, then strip off the filename portion. On Linux, callreadlink
on/proc/self/exe
for the main executable, or munge around in/proc/self/maps
for the mapping corresponding to your code segment for a dynamic library. On other OSes, I have no idea.只需传递相对文件名即可。它将相对于当前目录进行获取。
Just pass the relative file name. It will be taken relative to the current directory.