问题描述
我想要一个将相对路径转换为绝对路径的标准函数,如果可能的话,我想让它尽可能跨平台(所以我想避免调用外部库函数).这是为了防止路径利用.
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?
推荐答案
没有一个可以调用的通用函数,因为 C 或 C++ 标准库中没有这样的函数.在 Windows 上,您可以使用 GetFullPathName
.在 Linux、Mac OS X 和其他基于 *Unix 的系统上,您可以使用 realpath(3)
函数,作为奖励,它还可以解析沿途的符号链接.
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.
这篇关于安全跨平台功能获取规范化路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!