在Linux中,opendir
函数是用于打开一个目录流的标准库函数。结合其他相关函数,如readdir
和closedir
,可以实现目录树的遍历。以下是一个简单的示例代码,演示如何使用这些函数来遍历一个目录及其子目录中的所有文件和目录。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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) {
if (entry->d_type == DT_REG) {
printf("File: %s\n", entry->d_name);
} else if (entry->d_type == DT_DIR) {
// 忽略当前目录和父目录的特殊条目
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
printf("Directory: %s\n", full_path);
list_directory_contents(full_path); // 递归遍历子目录
}
}
}
// 关闭目录
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
opendir
: 打开指定路径的目录并返回一个DIR
指针。如果无法打开目录,则返回NULL
。
readdir
: 从目录流中读取下一个条目。每次调用都会返回一个指向dirent
结构的指针,该结构包含有关目录条目的信息。
closedir
: 关闭目录流。
递归遍历: 当遇到子目录时,程序会递归调用list_directory_contents
函数来遍历该子目录的内容。
perror
函数来打印系统错误信息。