温馨提示×

debian copendir示例怎么写

小樊
43
2026-09-19 03:43:37
栏目: 智能运维

在 Debian(其实是标准 POSIX/Linux C 语言环境)中,opendir 用于打开一个目录,通常和 readdirclosedir 配合使用。下面给你一个完整可编译的示例


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

#include <stdio.h>
#include <dirent.h>
#include <stdlib.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 opendir_example.c -o opendir_example
./opendir_example /etc

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

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

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

    dir = opendir(argv[1]);
    while ((entry = readdir(dir)) != NULL) {
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
        stat(path, &st);
        if (S_ISREG(st.st_mode)) {
            printf("文件: %s\n", entry->d_name);
        }
    }
    closedir(dir);
}

四、关键点说明

  • opendir:打开目录,返回 DIR*
  • readdir:读取目录项
  • closedir:关闭目录
  • 头文件:
    #include <dirent.h>
    

如果你想要 C++ 示例递归遍历目录过滤特定后缀文件,也可以告诉我。

0