Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 260
0xbadf00d Avatar asked Jun 15 '26 02:06

0xbadf00d


1 Answers

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.

like image 162
bdonlan Avatar answered Jun 18 '26 00:06

bdonlan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!