linux - 为什么有的文件stat结构的st_mode为0?
黄舟
黄舟 2017-04-17 13:48:58
[Linux讨论组]

功能很简单,列出当前给定目录"MyDirectory"里的文件和文件夹,就第一层深度。


用gdb看了下,有些st_mode为0,请问为什么呢?

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

int main(void)
{
    DIR *pDir = opendir("MyDirectory");
    struct dirent *pDirent;
    struct stat vStat;

    if (pDir == NULL)
    {
        printf("Can't open the directory \"MyDirectory\"");
        exit(1);
    }

    while ((pDirent = readdir(pDir)) != NULL)
    {
        stat(pDirent->d_name, &vStat);
        if (S_ISDIR(vStat.st_mode))
            printf("Directory: %s\n", pDirent->d_name);
        else
            printf("File: %s\n", pDirent->d_name);
    }

    closedir(pDir);
    return 0;
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
PHP中文网

答案在于stat调用失败!根据返回的errno表示没有这个文件或文件夹。
因为目前还是在当前目录,而不是在"MyDirectory"下。所以文件路径pathname就不存在。
解决方法有二:
一是在将MyDictory的名字也加进来:

char *directory = "MyDirectory";
size_t directory_length = strlen(directory);
char *path = malloc(directory_length + 1 + NAME_MAX);
strcpy(path, directory);
path[directory_length] = '/';
while ((pDirent = readdir(pDir)) != NULL) {
    strcpy(path + directory_length + 1, pDirent->d_name);
    if (stat(path, &vStat) == -1) {
        perror(path);
        continue;
    }
    …
}

二是进入该目录:

chdir("MyDictory");
大家讲道理

man 2 stat, 搜st_mode
S_ISDIR http://bbs.chinaunix.net/thread-628868-1-1.html

PS:APUE里面居然讲过这些,一点印象都没有,貌似从来都没需求判断目录之类的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号