SAFELY get path to running executable in windows API

蓝咒 提交于 2021-02-09 11:48:13

问题


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?


回答1:


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




回答2:


GetModuleFilename returns the number of characters copied to your buffer. If it's less than the size of your buffer, you're fine. If it's equal to the size of your buffer, allocate a larger buffer and try again.



来源:https://stackoverflow.com/questions/4841546/safely-get-path-to-running-executable-in-windows-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!