在Linux中,readdir
函数用于读取目录中的条目。但是,readdir
本身并不支持递归读取子目录。要实现递归目录读取,你需要结合其他函数,如opendir
、closedir
和dirent.h
头文件中的结构体。
以下是一个使用C语言实现的递归目录读取示例:
#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) {
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;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", path_stat.path);
list_directory_contents(path_stat.path);
} else {
printf("File: %s\n", path_stat.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;
}
这个程序接受一个目录路径作为参数,然后递归地列出该目录及其所有子目录中的文件和文件夹。注意,这个示例没有处理符号链接和其他特殊文件类型。在实际应用中,你可能需要根据需求进行相应的调整。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1296639.html