Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何检查文件(输入)是否在 C 中的程序目录中?首先我想我可以打开文件,但我不希望用户通过输入类似的内容来查看我的其他文件../important_dir/important_file,但如果用户执行类似./dir1/../file1. 这意味着,只要文件在当前目录中(没有子目录),就可以打开它。
../important_dir/important_file
./dir1/../file1
然后我四处寻找readdir,它可以用来查找当前目录中的所有内容,但是如果当前目录有很多文件,那么每次获取用户输入时查找文件名都会太慢。
readdir
有什么快速安全的方法可以做到这一点?
我认为 realpath 应该做这项工作。如果可能的话,我明天会发布解决方案。
您可以只使用stat()来检查文件的状态。如果有问题的文件不存在并设置errno为,它将返回 -1 ENOENT。
stat()
errno
ENOENT
char filename[] = "myfile"; struct stat s = {0}; if (!(stat(filename, &s) { if (ENOENT == errno) perror("file does not exist."); }