Safe cross-platform function to get normalized path

一个人想着一个人 提交于 2019-12-19 19:23:23

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7129096/safe-cross-platform-function-to-get-normalized-path

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