opendir 函数本身无法实现递归目录遍历,需要结合 readdir、closedir 和 stat (或 lstat 避免符号链接问题) 函数,并使用递归调用来实现。以下是一个改进的 C 语言示例,它能够更稳健地处理目录遍历,包括符号链接:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <dirent.h>#include <sys/stat.h>#include <limits.h> // for PATH_MAXvoid list_directory_contents(const char *path) { DIR *dir; struct dirent *entry; struct stat path_stat; char full_path[PATH_MAX]; 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 避免缓冲区溢出 if (snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name) >= sizeof(full_path)) { fprintf(stderr, "Path too long: %s/%sn", path, entry->d_name); continue; } if (lstat(full_path, &path_stat) == -1) { // 使用 lstat 处理符号链接 perror("lstat"); continue; } if (S_ISDIR(path_stat.st_mode)) { list_directory_contents(full_path); } else if (S_ISREG(path_stat.st_mode)) { // 只打印常规文件 printf("%sn", full_path); } else if (S_ISLNK(path_stat.st_mode)) { printf("Symbolic link: %sn", full_path); // 处理符号链接 } else { printf("Other file type: %sn", 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;}
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。