温馨提示×

debian copendir怎么写示例

小樊
39
2026-09-12 21:33:55
栏目: 智能运维

在 Debian(其实是标准 POSIX/Linux C 语言环境)里,遍历目录一般用 opendir() + readdir() + closedir()。下面给你一个完整可编译的示例


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

代码(listdir.c)

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

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

    if (argc < 2) {
        fprintf(stderr, "用法: %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;
}

编译(Debian)

gcc listdir.c -o listdir

运行

./listdir /etc

只列出普通文件(可选改进)

#include <sys/stat.h>

struct stat st;
char path[1024];

while ((entry = readdir(dir)) != NULL) {
    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);
    }
}

常见注意点

  • ... 也会被 readdir 读出来
  • dirent.h 是 POSIX 标准,Debian 默认支持
  • 遍历大量文件时注意及时 closedir

如果你想要:

  • 递归遍历目录
  • C++ 示例
  • 只找某种后缀文件

可以继续问我。

0