插件窝 干货文章 如何用copendir遍历目录

如何用copendir遍历目录

递归 遍历 目录 include 196    来源:    2025-05-05

使用 copendir 遍历目录

copendir 并不是标准的 C 或 POSIX 函数,你可能指的是 opendir 函数。在 C 语言中,我们使用 opendirreaddirclosedir 来遍历目录。下面是一个完整的示例:

使用 opendir/readdir/closedir 遍历目录

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;

    if (argc < 2) {
        printf("Usage: %s directory_name\n", argv[0]);
        return 1;
    }

    // 打开目录
    if ((dir = opendir(argv[1])) == NULL) {
        perror("opendir");
        return 1;
    }

    printf("Contents of directory '%s':\n", argv[1]);

    // 读取目录内容
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    // 关闭目录
    closedir(dir);

    return 0;
}

递归遍历目录(包括子目录)

如果需要递归遍历所有子目录,可以使用以下代码:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>

void listFiles(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char fullpath[PATH_MAX];

    if ((dir = opendir(path)) == NULL) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 跳过 "." 和 ".."
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;

        // 构建完整路径
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        // 获取文件信息
        if (lstat(fullpath, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        printf("%s\n", fullpath);

        // 如果是目录,递归调用
        if (S_ISDIR(statbuf.st_mode)) {
            listFiles(fullpath);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s directory_name\n", argv[0]);
        return 1;
    }

    listFiles(argv[1]);
    return 0;
}

注意事项

  1. 这些代码使用了 POSIX 标准函数,在 Linux/Unix 系统上可用
  2. Windows 系统上有不同的 API(如 FindFirstFile/FindNextFile)
  3. 递归版本中使用了 lstat 而不是 stat 来正确处理符号链接
  4. 实际应用中应该添加更多的错误检查
  5. 对于大型目录结构,递归版本可能会消耗较多栈空间

如果你确实需要 Windows 版本的目录遍历代码,或者有其他特定需求,请告诉我,我可以提供相应的解决方案。