Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAFELY get path to running executable in windows API

Tags:

c++

windows

Hey, I'm trying to get the path to a dll located in the same folder as my exe file. The way to go seems to be to use one of either QueryFullProcessImageName() or GetModuleFileName() to get the path to the running executable and then use string manipulation to make it a path to the required library instead.

Unfortunately, neither of these two functions provide a way to find out in advance the size buffer required. I've tried passing zero in for the nSize parameter, but this doesn't have the desired effect.

What's the best practice way of doing this?

like image 284
KJ Tsanaktsidis Avatar asked Feb 03 '26 22:02

KJ Tsanaktsidis


1 Answers

In practice you can use Windows API MAX_PATH as your buffer size, perhaps add 1 for extra safety.

In theory a Windows path can be much larger. As I recall MAX_PATH is like 270 or thereabouts, while in the NTFS file system a path can be up to around (roughly) 32767 chars. However, for that large size it has to be handled as Unicode, and, importantly, Windows Explorer does not support such large paths, so it's not an issue in practice.

In practice, again, if you should ever encounter such large path, apparently impossible to remove, then you can use the Unicode naming (there's a special prefix to use for long paths), and/or equivalent shortnames (DOS 8.3 names), and/or define logical drives to shorten the path, so that the directory/file can be removed.

Cheers & hth.,

like image 52
Cheers and hth. - Alf Avatar answered Feb 05 '26 12:02

Cheers and hth. - Alf



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!