温馨提示×

copendir在Ubuntu有何替代方案

小樊
39
2026-08-02 20:25:08
栏目: 智能运维

在 Ubuntu(Linux)下,如果你原本使用 copendir(推测是 opendir 的误写,或某些非标准 API),下面给你几种常见替代方案,按使用场景分类说明。


一、最常见替代:opendir + readdir(POSIX 标准)

如果你是想遍历目录,这是最标准、最通用的方式。

示例

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

int main() {
    DIR *dir = opendir(".");
    if (!dir) return 1;

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

替代 copendir 的最佳方案


二、如果你需要更多信息(文件类型、inode 等)

1️⃣ opendir + readdir + stat

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;
    struct stat st;

    while ((entry = readdir(dir)) != NULL) {
        stat(entry->d_name, &st);
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
}

三、现代替代方案(推荐)

glob(适合路径匹配)

#include <glob.h>
#include <stdio.h>

int main() {
    glob_t gl;
    glob("*.c", 0, NULL, &gl);

    for (int i = 0; i < gl.gl_pathc; i++)
        printf("%s\n", gl.gl_pathv[i]);

    globfree(&gl);
}

✔ 非常适合 通配符匹配


nftw(递归遍历目录)

#include <ftw.h>
#include <stdio.h>

int fn(const char *path, const struct stat *st, int type, struct FTW *ftwbuf) {
    printf("%s\n", path);
    return 0;
}

int main() {
    nftw(".", fn, 20, FTW_PHYS);
}

✔ 递归目录首选


四、如果你是 C++ 用户

1️⃣ std::filesystem(C++17+ ✅ 强烈推荐)

#include <filesystem>
#include <iostream>

int main() {
    for (auto &p : std::filesystem::directory_iterator(".")) {
        std::cout << p.path() << std::endl;
    }
}
g++ -std=c++17 test.cpp

五、如果你在找“拷贝目录”的功能

Linux 没有 copendir 这种 API,如果你是想:

✅ 拷贝目录内容

cp -r src dst

或在 C 中:

  • opendir
  • readdir
  • mkdir
  • open / read / write

六、总结对照表

需求 推荐方案
遍历目录 opendir + readdir
通配符 glob
递归遍历 nftw
C++ std::filesystem
命令行 find, cp -r

如果你能贴出 copendir 的来源代码或上下文(比如某个库、教材、Mac / BSD 系统),我可以给你更精确的等价替代方案

0