在 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 的最佳方案
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);
}
✔ 递归目录首选
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 中:
opendirreaddirmkdiropen / read / write| 需求 | 推荐方案 |
|---|---|
| 遍历目录 | opendir + readdir |
| 通配符 | glob |
| 递归遍历 | nftw |
| C++ | std::filesystem |
| 命令行 | find, cp -r |
如果你能贴出 copendir 的来源代码或上下文(比如某个库、教材、Mac / BSD 系统),我可以给你更精确的等价替代方案。