温馨提示×

ubuntu copendir需要头文件吗

小樊
49
2026-09-29 19:36:54
栏目: 智能运维

在 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;
}

编译

gcc test.c -o test

总结

  • ✅ 必须包含:<dirent.h>
  • 相关函数:readdir(), closedir(), rewinddir() 也都在 <dirent.h> 中
  • 错误处理常用:<stdio.h>(perror)

如果你是在写 C++,同样需要 #include <dirent.h>(不是 <dirent>)。

需要我给你一个完整的目录遍历示例吗?

0 踩