温馨提示×

ubuntu copendir需要包含什么头文件

小樊
40
2026-10-14 11:15:06
栏目: 智能运维

在 Ubuntu(Linux)下使用 opendir() 函数,需要包含以下头文件:

#include <sys/types.h>
#include <dirent.h>

说明

  • opendir() 用于打开一个目录,返回一个 DIR *
  • <dirent.h> 是必须的头文件,提供 opendir、readdir、closedir 等函数声明
  • <sys/types.h> 通常用于定义 off_t、ino_t 等类型(部分系统可省略,但推荐包含)

示例

#include <stdio.h>
#include <sys/types.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

如果你是在 C++ 中使用,也可以写:

#include <dirent.h>

需要我补充 readdir / closedir 或递归遍历目录的示例吗?

0 踩