温馨提示×

debian copendir怎么读取文件

小樊
35
2026-09-16 03:42:43
栏目: 智能运维

在 Debian(其实任何 Linux 系统都通用)下,opendir 是用来打开目录,而不是读取文件内容的
如果你想“读取目录中的文件”,一般流程是:

  1. opendir 打开目录
  2. readdir 读取目录项(文件名)
  3. 再用 open / fopen 去读取具体文件内容

一、opendir + readdir 基本用法(C 语言)

#include <stdio.h>
#include <dirent.h>

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir("/tmp");
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

✅ 这样可以列出目录里的所有文件名
❌ 但还没有读取文件内容


二、读取某个文件内容(在 readdir 之后)

#include <stdio.h>
#include <dirent.h>
#include <string.h>

int main() {
    DIR *dir = opendir("/tmp");
    struct dirent *entry;
    char path[256];
    FILE *fp;
    char buf[1024];

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

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

        fp = fopen(path, "r");
        if (!fp) continue;

        printf("=== %s ===\n", path);
        while (fgets(buf, sizeof(buf), fp)) {
            printf("%s", buf);
        }
        fclose(fp);
    }

    closedir(dir);
    return 0;
}

三、常见误解澄清

opendir 不能读取文件
opendirreaddiropen/fopen

如果你想要:

  • 只读取一个文件 → 直接用 open() / fopen()
  • 遍历目录并读文件opendir + readdir + fopen

四、Debian 下编译

gcc test.c -o test
./test

如果你是想:

  • 只读普通文件(跳过目录)
  • 递归子目录
  • 用 C++ / shell / Python

可以告诉我,我可以给你对应版本。

0