如何检查文件是否在特定目录或其子目录中 C

How to check if a file is in a specific directory or its subdirectories in C

我正在构建自己的 shell 我想知道:我如何知道命令是否在目录“/bin”及其子目录中。 我想实现一个函数 char* path_to_command(char* commandname) 其中 return 参数中给出的命令路径。

我一直在寻找确定特定文件是否在目录中的函数(如 fopen 或 access)。但是这些函数只是告诉我们文件是否只在目录中。 我正在考虑使用 fopen 的递归函数,我将不得不在其中使用 strcat 很多时间。 我相信有更好的解决方案。

英语不是我的母语,如有错误,我深表歉意。 谢谢你。

需要看目录内容,看函数opendir / readdir / closedir (#include <dirent.h>)

{编辑添加}

请注意,当您扫描目录的内容时,您将到达目录“.”。和“..”,不要递归进入它们,因为“.”是当前目录,“..”是上层目录(除了“/”,其中“..”也是“/”)

您不仅可以在其上使用 opendir(3) & readdir(3) & closedir but you probably want to construct some file path in a string (using string routines like snprintf or asprintf) and use stat(2) or access(2)(因为 readdir returns 一个目录条目,其 d_name 您将与包含目录的路径组合) .

您也可以使用 nftw(3).

但是,在 shell 中,您只想迭代 PATH variable, and append the program name to each of them. For that point a recursive descent is not needed. And there is also execvp(3).

的组件

不要自己写递归函数,更喜欢使用标准nftw:

NAME

nftw - walk a file tree

SYNOPSIS

#include <ftw.h>

int nftw(const char *path, int (*fn)(const char *,
         const struct stat *, int, struct FTW *), int fd_limit, int flags);

DESCRIPTION

The nftw() function shall recursively descend the directory hierarchy rooted in path.

但是,对于标准 shell 来说,不需要递归搜索(最糟糕的是,这对任何用户来说都是非常奇怪的),您只需要在 PATH 环境中提到的目录中搜索变量。