【问题标题】:Check if a file is inside a directory in C [duplicate]检查文件是否在C目录中[重复]
【发布时间】:2013-11-30 02:48:18
【问题描述】:
在我正在编写的 C 程序中,我需要检查文件是否包含在目录中。
这是因为文件路径是由用户提供的,我不希望他能够通过提供诸如“../../whatever”或“~/. .bashrc”。
有没有办法只使用 ANSI C 和 POSIX 来做到这一点(我试图避免使用第三方库)?
或者我应该检查路径字符串吗?这是我的第一个想法,但听起来有点复杂(例如:包含“.”的路径可以,但包含“..”的路径不行)。
谢谢
【问题讨论】:
标签:
c
file
security
directory
posix
【解决方案1】:
符号链接呢?
我认为这里真正的问题是您想将可能的路径转换为其“绝对”路径。幸运的是,有一个功能可以帮助您。
来自http://linux.die.net/man/3/realpath:
realpath() expands all symbolic links and resolves references to /./, /../ and extra '/'
characters in the null-terminated string named by path to produce a canonicalized absolute
pathname. The resulting pathname is stored as a null-terminated string, up to a maximum of
PATH_MAX bytes, in the buffer pointed to by resolved_path. The resulting path will have no
symbolic link, /./ or /../ components.
因此,您可以将他们尝试访问的路径转换为绝对路径,然后检查该绝对路径是否被允许。还有另一种称为 getcwd() 的方法,您可以使用它来确定当前工作目录。