开发者

Open file relative to executed module

I know, it isn't the best idea to open a file constraining it to be placed in the same directory like the execute开发者_高级运维d 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?


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, call readlink 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜