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

Linux系统stat命令与C语言stat函数返回文件元数据结果不一致问题咨询

问题根源:相对路径 vs 绝对路径的误用

你遇到的问题核心是路径处理错误:当你用opendir("/")打开根目录后,readdir返回的entry->d_name是根目录下的文件名(比如usr),但你直接把这个名字传给stat函数时,stat会在程序的当前工作目录(而不是你打开的/目录)下去查找这个文件,所以你实际获取的是当前工作目录下usr目录的元数据,而非根目录下的/usr,这就是时间信息和stat /usr命令不一致的原因。

验证问题的简单方法

在你的stat调用后加上错误检查,就能直观发现问题:

if (stat(entry->d_name, &pFilestat) == -1) {
    perror("stat() error");
}

如果你的当前工作目录不是/,那么对于usr这个条目,大概率会报错(除非当前目录恰好也有个usr目录);而你现在得到了时间,说明程序运行时的当前目录下确实存在一个usr目录,它的时间就是你看到的那些值。

修正方案:构造绝对路径

要正确获取根目录下文件的元数据,你需要把/和entry->d_name拼接成完整的绝对路径,再传给stat。修正后的代码如下:

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

int getDirContent(){
    DIR *dir;
    struct dirent *entry;
    struct stat pFilestat;
    const char *root_path = "/";
    
    if ((dir = opendir(root_path)) == NULL) {
        perror("opendir() error");
        return -1;
    } 
    
    puts("contents of root:");
    /* Read directory entries */
    while ((entry = readdir(dir)) != NULL){
        // 跳过.和..,避免重复处理当前/父目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }
        
        /* 构造完整绝对路径 */
        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s%s", root_path, entry->d_name);
        
        /* 调用stat并检查错误 */
        if (stat(full_path, &pFilestat) == -1) {
            fprintf(stderr, "stat failed for %s: %s\n", full_path, strerror(errno));
            continue;
        }
        
        printf("%s\n", entry->d_name);
        /* 输出目录时间信息 */
        if (S_ISDIR(pFilestat.st_mode)){
            printf("Access: %s",ctime(&pFilestat.st_atime));
            printf("Modify: %s",ctime(&pFilestat.st_mtime));
            printf("Change: %s",ctime(&pFilestat.st_ctime));
        }
    }
    closedir(dir);
    return 0;
}

额外注意事项

  • 记得包含#include <limits.h>来使用PATH_MAX宏,它定义了系统允许的最长路径长度。
  • 处理readdir返回的.和..条目,避免不必要的重复处理。
  • 始终检查系统调用的返回值(比如stat、opendir),这能帮你快速定位各类路径或权限错误。
  • ctime函数返回的字符串已经包含换行符,所以你的printf不需要额外添加换行。

这样修改后,你获取的/usr时间信息就会和stat /usr命令的结果完全一致了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 08:37:44