copendir
是一个用于打开目录的函数,它返回一个指向 DIR
结构的指针,该结构包含了目录流的信息。在递归遍历目录时,copendir
通常与 readdir
和 closedir
函数一起使用,以读取目录内容并检查每个条目是否为子目录。如果是子目录,则递归调用遍历函数。
以下是一个使用 copendir
递归遍历目录的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.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) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path of the entry
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// Get the file status
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// If it's a directory, recurse
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path);
} else {
// Otherwise, print the file name
printf("File: %s\n", 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;
}
在这个示例中,list_directory_contents
函数接受一个目录路径作为参数,打开该目录,并使用 readdir
函数读取其内容。对于每个条目,它使用 stat
函数获取文件状态,以确定它是文件还是目录。如果是目录,它会打印目录名并递归调用自身。如果是文件,它将打印文件名。注意,这个函数会跳过当前目录(.
)和父目录(..
)的条目。
要使用这个程序,你需要将其编译为可执行文件,并在命令行中提供要遍历的目录路径作为参数。例如:
gcc -o listdir listdir.c
./listdir /path/to/directory
这将递归地列出指定目录及其所有子目录中的文件和目录。