温馨提示×

ubuntu copendir怎么使用

小樊
47
2026-09-05 17:59:16
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 是 C 语言标准库(dirent.h) 中用于打开目录的函数,通常和 readdir、closedir 配合使用来遍历目录。

下面从 函数原型 → 基本用法 → 完整示例 → 常见错误 给你讲清楚。


一、opendir 函数原型

#include <dirent.h>

DIR *opendir(const char *name);

参数

  • name:要打开的目录路径(如 "/home/user" 或 ".")

返回值

  • 成功:返回 DIR *(目录流指针)
  • 失败:返回 NULL,并设置 errno

二、配合使用的函数

struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

三、最基本示例(列出目录内容)

示例:列出当前目录下的所有文件

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

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

编译运行

gcc test.c -o test
./test

四、读取指定目录

dir = opendir("/home/ubuntu");

如果目录不存在或权限不足:

perror("opendir");

常见错误:

  • ENOENT:目录不存在
  • EACCES:权限不足

五、过滤 . 和 ..

while ((entry = readdir(dir)) != NULL) {
    if (strcmp(entry->d_name, ".") == 0 ||
        strcmp(entry->d_name, "..") == 0)
        continue;

    printf("%s\n", entry->d_name);
}

六、判断是文件还是目录(进阶)

#include <sys/stat.h>

struct stat st;
stat(entry->d_name, &st);

if (S_ISDIR(st.st_mode))
    printf("[DIR] %s\n", entry->d_name);
else
    printf("[FILE] %s\n", entry->d_name);

七、常见使用场景

✅ 遍历目录
✅ 写文件管理器
✅ 扫描日志文件
✅ 写递归目录遍历程序


八、总结

函数 作用
opendir 打开目录
readdir 读取目录项
closedir 关闭目录

如果你愿意,我也可以:

  • ✅ 给你 递归遍历目录示例
  • ✅ 用 C++ / Python 实现同样功能
  • ✅ 讲 opendir 在内核层怎么工作

你想看哪一个?

0 踩