在Ubuntu中,你可以使用C语言的dirent.h
库中的opendir()
、readdir()
和closedir()
函数来遍历子目录
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个命令行参数,即要遍历的目录路径。它首先使用opendir()
函数打开目录,然后使用readdir()
函数读取目录中的每个条目。最后,使用closedir()
函数关闭目录。
要编译此程序,请将其保存为list_directory_contents.c
,然后在终端中运行以下命令:
gcc -o list_directory_contents list_directory_contents.c
现在,你可以使用以下命令运行程序,遍历指定目录及其子目录:
./list_directory_contents /path/to/directory
请注意,这个程序只会列出指定目录的直接内容。如果你想要递归地遍历所有子目录,你需要编写一个递归函数来实现这个功能。