Open file relative to executed module

I know that it is not a good idea to open a file restricting its placement in the same directory as the executable module. But, there is a tool, I was ordered to program, with the exact specifications given.

There is a parameter for the path to the file, which can be an absolute path to the file or just the file name if it is in the current directory.

I do not want to use the GetCurrentDirectory function for WinAPI to maintain portability. The tool should fail if the file cannot be opened.

I usually use boost :: filesystem as an I / O library. Thus, I am not very familiar with the std library.

My first idea was to simply pass the file path to std :: ifstream :: open (). But it doesn't seem to work for relative paths.

What can I do to cover my requirements?

+3
source share
2 answers

Unfortunately, there is no easy portable way to do this. In particular, it GetCurrentDirectorymay not return the same directory as your executable module - in windows, simply opening the file selection dialog will change the current directory! On other platforms, you are unlikely to start working in the same directory (then, perhaps, you also do not have write access, but this also applies to modern windows ...)

, , GetModuleFileName, , . Linux readlink /proc/self/exe /proc/self/maps , . .

+3

. .

-3

Source: https://habr.com/ru/post/1789237/


All Articles