在 Debian 系统中,你可以使用 readdir
函数来遍历目录及其子目录。readdir
是一个 POSIX 标准库函数,用于读取目录流中的条目。下面是一个使用 C 语言编写的示例程序,演示如何使用 readdir
遍历目录及其子目录:
#include#include #include #include #include void list_directory_contents(const char *path) { DIR *dir; struct dirent *entry; struct stat path_stat; dir = opendir(path); if (!dir) { perror("opendir"); return; } while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } snprintf(path_stat_path, sizeof(path_stat_path), "%s/%s", path, entry->d_name); if (stat(path_stat_path, &path_stat) == -1) { perror("stat"); continue; } printf("%s\n", path_stat_path); if (S_ISDIR(path_stat.st_mode)) { list_directory_contents(path_stat_path); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return EXIT_FAILURE; } list_directory_contents(argv[1]); return EXIT_SUCCESS; }
要编译此程序,请将其保存为 list_directory_contents.c
,然后在终端中运行以下命令:
gcc -o list_directory_contents list_directory_contents.c
现在,你可以使用以下命令运行程序,列出指定目录及其子目录的内容:
./list_directory_contents /path/to/directory
请注意,这个示例程序仅适用于 POSIX 兼容的系统,如 Debian。在其他系统上,可能需要使用不同的函数和方法。