Safe cross-platform function to get normalized pat

2019-02-23 04:26发布

问题:

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.