温馨提示×

如何用copendir读Ubuntu目录

小樊
52
2026-08-02 19:49:14
栏目: 智能运维

在 Ubuntu(Linux)下,copendir 并不是一个标准函数。你可能想用的是 opendir / readdir / closedir 这一套 POSIX 接口来读取目录。

下面我按正确用法给你一个完整示例,并顺带说明常见误区。


一、正确方式:用 opendir 读目录(推荐)

1️⃣ 头文件

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

2️⃣ 示例代码(读取 Ubuntu 当前目录)

#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;
}

3️⃣ 编译运行

gcc readdir.c -o readdir
./readdir

输出示例:

.
..
file1.txt
test

二、常见误解:copendir 是什么?

✅ 结论:

Linux / Ubuntu 中没有 copendir 这个函数

你可能遇到的情况:

情况 说明
拼写错误 实际是 opendir
Windows 旧接口 Windows 曾有 _copendir
第三方库 某些非标准封装

✅ Linux 下只认:

opendir()
readdir()
closedir()

三、进阶:只读取普通文件(排除 . 和 ..)

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 普通文件
            printf("File: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

四、目录类型说明(d_type)

类型 含义
DT_REG 普通文件
DT_DIR 目录
DT_LNK 符号链接

⚠️ 注意:d_type 在某些文件系统上可能不可用,必要时用 stat()。


五、如果你是想用 C++ / Python / Shell

C++

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

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

Python

import os
for f in os.listdir("."):
    print(f)

六、总结一句话

✅ Ubuntu 下读目录:

用 opendir + readdir + closedir,没有 copendir

如果你愿意,可以告诉我:

  • 是 C / C++ / Python
  • 是否要 递归遍历
  • 是否要 过滤文件类型

我可以直接给你定制代码。

0 踩