You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下C语言区分文件与目录异常:全部识别为目录的问题排查

问题:无法区分目录下的文件与文件夹(stat使用错误)

你的核心问题是调用stat()时传入了错误的路径,导致每次获取的都是目标目录本身的属性,而非当前遍历的文件/子目录信息。

错误原因解释

stat()函数需要接收文件或目录的完整路径(或能准确定位目标的相对路径),它会查询文件系统中对应路径的元数据并填充到struct stat结构体中。你当前代码里stat(dir, &info)始终传入的是父目录的路径,所以每次获取的都是父目录的属性,自然所有条目都被判定为目录。

修正后的代码

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <limits.h> // 包含PATH_MAX定义

void scan(const char *dir) {
    DIR *directory;
    struct dirent *file;
    struct stat info;
    char full_path[PATH_MAX]; // 存储完整路径的缓冲区

    directory = opendir(dir);
    if (directory == NULL) {
        printf("Cannot open directory: %s\n", dir);
        return;
    }

    while ((file = readdir(directory)) != NULL) {
        if (file->d_name[0] == '.') {
            // 跳过隐藏文件、当前目录(.)和上级目录(..)
            continue;
        }

        // 拼接父目录与当前条目,生成完整路径
        snprintf(full_path, sizeof(full_path), "%s/%s", dir, file->d_name);

        if (stat(full_path, &info) == -1) {
            printf("Failed to get info for %s\n", file->d_name);
            perror("ERROR");
            continue; // 跳过当前条目,继续遍历下一个
        }

        // 判断文件类型
        if (S_ISREG(info.st_mode))
            printf("File: ");
        else if (S_ISDIR(info.st_mode))
            printf("Dir: ");
        // 可扩展支持其他文件类型:如S_ISLNK(软链接)、S_ISCHR(字符设备)等

        printf("%s\n", file->d_name);
    }
    closedir(directory);
}

关键修正点

  1. 路径拼接:用snprintf安全拼接父目录路径和当前条目名称,生成完整路径,避免缓冲区溢出。
  2. 错误处理优化:stat失败时跳过当前条目,避免使用无效的info结构体进行类型判断。
  3. 类型判断逻辑:用else if替代多个独立if,避免同时打印多个类型标记(极端情况下可能出现的异常)。

内容的提问来源于stack exchange,提问作者Devin Bowen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:52:58