温馨提示×

ubuntu copendir要包含头文件吗

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

在 Ubuntu(Linux)下使用 opendir() 函数是需要包含头文件的。

opendir 是 POSIX 标准中的目录操作函数,声明在:

#include <dirent.h>

基本用法示例

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

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

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

    closedir(dir);
    return 0;
}

编译方式(Ubuntu)

gcc test.c -o test
./test

小结

  • ✅ 必须包含 <dirent.h>
  • 相关函数:readdir, closedir, rewinddir 也都在 <dirent.h> 中
  • 编译一般不需要额外链接库(glibc 默认包含)

如果你是在 C++ 里用,也可以 #include <dirent.h>(不是 <dirent>)。

需要我给你一个完整的“遍历目录”或“递归遍历子目录”的示例吗?

0 踩