温馨提示×

如何用ubuntu copendir读目录

小樊
42
2026-10-05 14:27:14
栏目: 智能运维

在 Ubuntu(Linux)下,如果你说的是 用 C 语言读取目录,通常是用 opendir / readdir 这套 POSIX 接口,而不是“copendir”。下面给你一个完整、可直接编译运行的示例。


一、基本用法(opendir + readdir)

示例代码 listdir.c

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;

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

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

二、编译与运行

gcc listdir.c -o listdir
./listdir /etc

输出示例:

.
..
passwd
hosts
resolv.conf
...

三、只列出普通文件(可选)

#include <sys/stat.h>
#include <string.h>

// 在 while 中加判断
struct stat st;
char path[1024];

snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
    printf("%s\n", entry->d_name);
}

四、常见函数说明

函数 作用
opendir() 打开目录,返回 DIR*
readdir() 读取一个目录项
closedir() 关闭目录
struct dirent 目录项结构

五、如果你指的是别的

  • Python:os.listdir() 或 pathlib
  • C++17:std::filesystem::directory_iterator
  • shell:ls / find

如果你说的 “copendir” 是某个特定库(比如某些封装库),可以告诉我具体名称,我可以给你对应的用法。

0 踩