温馨提示×

ubuntu copendir如何包含头文件

小樊
34
2026-09-08 15:29:25
栏目: 智能运维

在 Ubuntu(Linux)下使用 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

补充说明

  • opendir() 属于 POSIX 标准,不是 C 标准库
  • 相关函数所在头文件:
    • opendir, readdir, closedir<dirent.h>
    • stat(常用配合) → <sys/stat.h>
    • 错误输出 perror<stdio.h>

如果你是在 C++ 里用,也可以:

#include <dirent.h>

需要我给你一个递归遍历目录的例子吗?

0