温馨提示×

怎样遍历ubuntu copendir结果

小樊
43
2026-09-23 22:42:04
栏目: 智能运维

在 Ubuntu(Linux)下,如果你用的是 C 语言 的 opendir / readdir 来遍历目录,一般流程是这样的:


1. 基本步骤

  1. opendir() 打开目录
  2. readdir() 逐个读取目录项
  3. 处理每个文件/子目录
  4. closedir() 关闭目录

2. 示例代码(C 语言)

#include <stdio.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char *argv[])
{
    const char *path = ".";  // 当前目录
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

3. 编译与运行

gcc listdir.c -o listdir
./listdir

4. 常见补充

判断文件类型

#include <sys/stat.h>

struct stat st;
char fullpath[256];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
stat(fullpath, &st);

if (S_ISDIR(st.st_mode))
    printf("[DIR] %s\n", entry->d_name);
else
    printf("[FILE] %s\n", entry->d_name);

递归遍历(简单版)

可以在 S_ISDIR 时再次调用 opendir


5. 如果你用的是其他语言

  • C++:std::filesystem::directory_iterator
  • Shell:for f in *; do ...
  • Python:os.listdir / os.scandir

如果你说的 “copendir” 是指某个特定库(比如某些封装库),可以告诉我具体名称,我可以给更针对性的示例。

0 踩