温馨提示×

ubuntu copendir能用于c加加吗

小樊
43
2026-10-08 13:08:38
栏目: 智能运维

在 Ubuntu(Linux)上,opendir 可以用于 C++,因为 C++ 可以调用 C 标准库和 POSIX 接口。

1. opendir 是什么

opendir 是 POSIX 标准函数,声明在:

#include <dirent.h>

原型:

DIR *opendir(const char *name);

它用于打开一个目录,配合 readdir、closedir 使用。


2. 在 C++ 中如何使用

C++ 完全兼容 C,所以可以直接用:

#include <iostream>
#include <dirent.h>

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

    struct dirent *entry;
    while ((entry = readdir(dir)) != nullptr) {
        std::cout << entry->d_name << std::endl;
    }

    closedir(dir);
    return 0;
}

编译:

g++ test.cpp -o test

3. C++ 中更推荐的方式(C++17 起)

如果你用的是 C++17 及以上,更推荐用标准库:

#include <filesystem>
#include <iostream>

int main() {
    for (const auto &p : std::filesystem::directory_iterator(".")) {
        std::cout << p.path() << std::endl;
    }
}

编译(Ubuntu 旧版本可能需要):

g++ test.cpp -o test -std=c++17 -lstdc++fs

(Ubuntu 20.04+ 一般不需要 -lstdc++fs)


4. 总结

  • ✅ opendir 可以在 Ubuntu 的 C++ 中使用
  • ✅ 它是 POSIX C 接口,C++ 直接兼容
  • ✅ 新项目建议用 std::filesystem

如果你需要 递归遍历目录 或 过滤文件类型 的示例,也可以告诉我。

0 踩