温馨提示×

linux readdir在c++怎么用

小樊
39
2026-09-17 20:04:06
栏目: 编程语言

在 Linux 下使用 C/C++ 读取目录,readdir 是 POSIX 标准库提供的函数,配合 opendir / closedir 使用。下面给你一个完整、常见、可直接用的示例


一、基本头文件

#include <iostream>
#include <dirent.h>
#include <cstring>
#include <sys/types.h>

二、基本用法(C++ 示例)

#include <iostream>
#include <dirent.h>

int main() {
    DIR* dir = opendir(".");  // 打开当前目录
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
        std::cout << entry->d_name << std::endl;
    }

    closedir(dir);
    return 0;
}

三、关键函数说明

1️⃣ opendir

DIR* opendir(const char* path);
  • 成功:返回目录流指针
  • 失败:返回 NULL

2️⃣ readdir

struct dirent* readdir(DIR* dirp);
  • 每次调用返回一个目录项
  • 到结尾返回 NULL

3️⃣ struct dirent 常用字段

struct dirent {
    ino_t          d_ino;
    off_t          d_off;
    unsigned short d_rendtl;
    unsigned char  d_type;
    char           d_name[256];
};

常用:

  • d_name:文件名
  • d_type:文件类型(可选)

四、过滤 ...

while ((entry = readdir(dir)) != nullptr) {
    if (strcmp(entry->d_name, ".") == 0 ||
        strcmp(entry->d_name, "..") == 0)
        continue;

    std::cout << entry->d_name << std::endl;
}

五、判断文件类型(推荐)

#include <sys/stat.h>

while ((entry = readdir(dir)) != nullptr) {
    struct stat st;
    stat(entry->d_name, &st);

    if (S_ISDIR(st.st_mode))
        std::cout << "[DIR] ";
    else
        std::cout << "[FILE] ";

    std::cout << entry->d_name << std::endl;
}

六、C++17 更现代写法(可选)

如果你可以用 C++17:

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

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

✅ 更安全、跨平台
❌ 需要 -std=c++17 -lstdc++fs(老版本 GCC)


七、编译方式

g++ readdir_example.cpp -o readdir_example

如果你有具体需求(比如递归遍历目录只找某种文件统计大小),可以告诉我,我给你更针对性的代码。

0