温馨提示×

ubuntu copendir怎么获取文件

小樊
35
2026-09-17 19:41:04
栏目: 智能运维

在 Ubuntu(Linux)下使用 C 语言编程时,opendir 本身只能打开目录,并不能直接“获取文件”。
正确的流程是:

opendir → readdir → 判断是否是文件 → 获取文件信息


一、基本用法

1️⃣ 打开目录

#include <dirent.h>

DIR *dir = opendir("/path/to/dir");
if (dir == NULL) {
    perror("opendir");
    return -1;
}

2️⃣ 读取目录项(文件和子目录)

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

⚠️ readdir 返回的是 目录项,包括:

  • 普通文件
  • 子目录
  • 符号链接
  • ...

二、如何“获取文件”(区分文件和目录)

方法 1:使用 stat(最常用 ✅)

#include <sys/stat.h>

struct stat st;
char path[256];

while ((entry = readdir(dir)) != NULL) {
    snprintf(path, sizeof(path), "%s/%s", "/path/to/dir", entry->d_name);

    if (stat(path, &st) == -1)
        continue;

    if (S_ISREG(st.st_mode)) {
        printf("文件: %s\n", entry->d_name);
    }
}

判断类型宏

含义
S_ISREG(m) 普通文件
S_ISDIR(m) 目录
S_ISLNK(m) 符号链接

方法 2:使用 d_type(更快,但不一定全支持)

while ((entry = readdir(dir)) != NULL) {
    if (entry->d_type == DT_REG) {
        printf("文件: %s\n", entry->d_name);
    }
}

⚠️ 某些文件系统(如某些网络文件系统)d_type 可能是 DT_UNKNOWN


三、完整示例(获取目录下所有文件)

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

int main() {
    DIR *dir = opendir(".");
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    char path[512];

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

        snprintf(path, sizeof(path), "./%s", entry->d_name);

        struct stat st;
        if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
            printf("文件: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

四、常见误区

❌ 以为 opendir 能直接拿到文件内容
opendir 只是打开目录,文件内容要用 open/read

❌ 忘记过滤 ...
✅ 必须手动跳过


如果你需要:

  • 递归遍历子目录
  • 按后缀过滤(.txt / .c)
  • C++ / Python 版本

告诉我,我可以直接给你代码。

0