在Ubuntu中,使用opendir
函数可以遍历目录。以下是一个简单的示例,展示了如何使用opendir
、readdir
和closedir
函数来遍历一个目录及其子目录中的所有文件和文件夹。
首先,确保你的程序包含了必要的头文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
然后,你可以使用以下代码来遍历目录:
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录的特殊条目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建完整的文件/目录路径
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// 获取文件/目录的详细信息
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// 打印文件/目录名称和类型
printf("%s %s\n", full_path, entry->d_name);
// 如果是目录,则递归遍历
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(full_path);
}
}
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;
}
将上述代码保存为list_directory_contents.c
,然后使用以下命令编译:
gcc list_directory_contents.c -o list_directory_contents
最后,运行编译后的程序并传入要遍历的目录路径:
./list_directory_contents /path/to/directory
这将打印出指定目录及其子目录中的所有文件和文件夹。