温馨提示×

怎么在Ubuntu使用copendir

小樊
40
2026-08-02 19:31:12
栏目: 智能运维

在 Ubuntu(Linux)里,opendir() 不是命令,而是一个 C 语言函数,用来打开目录并配合 readdir()closedir() 使用。下面给你一个从概念到示例的完整说明


一、opendir 是什么?

opendir() 用于打开一个目录流,定义在:

#include <dirent.h>

函数原型:

DIR *opendir(const char *name);
  • 成功:返回 DIR*
  • 失败:返回 NULL,并设置 errno

二、基本使用示例(C 程序)

1️⃣ 创建示例文件

nano listdir.c

2️⃣ 示例代码:列出目录内容

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("用法: %s <目录>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    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 listdir.c -o listdir
./listdir /home

输出示例:

.
..
user1
user2

... 是特殊目录)


四、关键函数说明

函数 作用
opendir() 打开目录
readdir() 读取目录项
closedir() 关闭目录
struct dirent 目录项结构

五、常见错误

❌ 忘记包含头文件

#include <dirent.h>

❌ 目录不存在

./listdir /not_exist

会输出:

opendir: No such file or directory

六、如果你只是想在终端“查看目录”

那其实不需要 opendir,直接用:

ls

ls -l

七、如果你用的是 C++

可以用 std::filesystem(C++17 以后):

#include <filesystem>
namespace fs = std::filesystem;

for (auto &p : fs::directory_iterator(".")) {
    std::cout << p.path() << std::endl;
}

如果你愿意,我可以帮你:

  • 写一个 递归遍历目录 的例子
  • 解释 struct dirent 的每个字段
  • 或对比 opendirfind / ls 的实现原理

你现在是 写 C 程序 还是 刚看到这个函数不太理解

0