开发者

Safe cross-platform function to get normalized path

开发者 https://www.devze.com 2023-03-29 04:34 出处:网络
I\'d like to have a standard function that will convert relative paths into absolute ones, and if possible I\'d like to make it as cross-platform as possible (so I\'d like to avoid call开发者_运维问答

I'd like to have a standard function that will convert relative paths into absolute ones, and if possible I'd like to make it as cross-platform as possible (so I'd like to avoid call开发者_运维问答ing external library functions). This is intended so it's possible to prevent path exploitations.

I am aware that such a function wouldn't be able to detect symbolic links, but I'm ok with that for my application.

I could roll my own code, but there might be some problems with e.g. how a platform handles encoding or variations of the "../" pattern.

Is there something like that already implemented?


There's not a single, universal function you can call, since there's no such function in the C or C++ standard libraries. On Windows, you can use GetFullPathName. On Linux, Mac OS X, and other *Unix-based systems, you can use the realpath(3) function, which as a bonus also resolves symbolic links along the way.

Beware: Any solution to this is only reliable in a single-threaded program. If you're using multiple threads, another can go out and change the working directory out from under you unexpectedly, changing the path name resolution.


I think the closest you're going to get to platform independence are the POSIX libraries. In particular you'll wanna check out unistd.h which unfortunately I don't believe has a 'normalized' path concept. If I remember correctly the standard itself doesn't even know much about directories much less relative ones.

To get better than that I think you'll need to roll your own path goodies.

0

精彩评论

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

关注公众号