温馨提示×

ubuntu copendir需要包含啥头文件

小樊
45
2026-09-11 13:48:52
栏目: 智能运维

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

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

说明

  • <dirent.h>必须,定义了 DIRstruct dirent 以及 opendir()readdir()closedir() 等函数声明。
  • <sys/types.h>:通常也建议包含,定义了 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

如果你还需要 stat()、文件属性相关功能,可以再包含 <sys/stat.h><unistd.h>

0