在 Ubuntu(Linux)下,如果你说的是 opendir()(用于打开目录、配合 readdir() 遍历目录),确实有多种替代方案,取决于你的使用场景(C/C++、Shell、Python 等)。
下面按常见情况说明。
open() + getdents() / getdents64()(底层替代)opendir() 本质是封装了这些系统调用。
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/dirent.h>
int fd = open("/path", O_RDONLY | O_DIRECTORY);
// 使用 syscall(SYS_getdents64, fd, buf, size);
✅ 优点:更底层、可控
❌ 缺点:复杂、不可移植
fts_open()(推荐用于递归遍历)比 opendir() 更适合递归目录遍历。
#include <fts.h>
char *paths[] = {"/path", NULL};
FTS *fts = fts_open(paths, FTS_PHYSICAL, NULL);
✅ 优点:支持递归、符号链接控制
✅ glibc 提供,Ubuntu 默认可用
nftw()(目录树遍历)#include <ftw.h>
nftw("/path", my_func, 20, FTW_DEPTH);
✅ 内建递归
❌ 接口偏旧
std::filesystem如果你用 C++17+:
#include <filesystem>
namespace fs = std::filesystem;
for (auto& p : fs::directory_iterator("/path")) {
std::cout << p.path() << "\n";
}
✅ 现代、跨平台
✅ Ubuntu 20.04+ 完全支持
如果你本来是在 Shell 脚本里用 opendir(其实没有这个命令),替代是:
ls -1 /path
find /path
或:
for f in /path/*; do
echo "$f"
done
import os
for name in os.listdir("/path"):
print(name)
或:
import pathlib
for p in pathlib.Path("/path").iterdir():
print(p)
opendir()✅ 以下情况继续用 opendir() 就好:
DIR*如果你能说明:
我可以给你最合适的方案或示例代码。