温馨提示×

ubuntu copendir怎么写代码

小樊
45
2026-10-20 05:07:26
栏目: 智能运维

在 Ubuntu(Linux)下使用 C 语言编写 opendir / readdir / closedir 的代码示例,下面是一个完整、常用的写法。


一、基本示例:列出目录下的所有文件

#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 /home

三、忽略 . 和 ..

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;
char path[256];

snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
stat(path, &st);

if (S_ISDIR(st.st_mode))
    printf("[目录] %s\n");
else if (S_ISREG(st.st_mode))
    printf("[文件] %s\n");

五、常用函数说明

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

如果你是 C++、递归遍历目录 或 过滤特定文件类型,我也可以继续帮你写。

0 踩