【问题标题】:How to find out the size of the files from a directory如何从目录中找出文件的大小
【发布时间】:2021-01-23 19:12:22
【问题描述】:

所以我有这段代码通过launchint显示我的树莓派上一个目录的所有文件,例如:“./Readdir /etc”。我需要修改它,以便它也打印文件的大小。我尝试添加另一个打印语句来打印这样的结构的大小:printf(sb.st_size),sb 被声明为struct stat sb,但这只会打印目录本身的大小。有谁知道如何帮助我?提前致谢!

/*  Readdir.c - Read the current working directory */

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

int main(int argc, char * argv[]) {
    if(argc>=2) {
        DIR *dirp = opendir(argv[1]) ;
        if ( dirp != NULL ) {
            struct dirent *dp ;
            while ((dp = readdir(dirp))) {
                char t;
                switch( dp->d_type ) {
                    case DT_BLK     : t = 'b' ; break ;
                    case DT_CHR     : t = 'c' ; break ;
                    case DT_DIR     : t = 'd' ; break ;
                    case DT_FIFO    : t = 'p' ; break ;
                    case DT_LNK     : t = 'l' ; break ;
                    case DT_REG     : t = '-' ; break ;
                    case DT_SOCK    : t = 's' ; break ;
                    case DT_UNKNOWN : t = 'u' ; break ;
                    default         : t = '?' ;
                }
                printf("%8d %c %s\n", (int)dp->d_ino, t, dp->d_name);
            }
            closedir(dirp);
        }
        return 0;
    } else {
        printf("usage: %s dir\n", argv[0]);
        return 1;
    }
}

【问题讨论】:

  • 你试过统计每个文件吗?
  • 统计?抱歉,我真的很讨厌 C,这是我第一次使用它,所以我不明白你的意思。
  • 您是否尝试调用函数stat 来询问有关每个文件的信息?而不是仅仅询问有关目录的信息?
  • 我该怎么做?
  • 当您调用 stat 时,您会告诉它您想要获取信息的路径,对吧?

标签: c linux raspberry-pi4


【解决方案1】:

dp-&gt;d_type 字段为:DT_REG

然后

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat  fileStat;
if( ! stat( dp->d_name, &fileStat ) )
{
    printf( "%d\n", fileStat.st_size );
}

【讨论】:

  • 由于dp-&gt;d_name 是相对于目录的,您需要在目录名称前面加上fstatat(dirfd(dirp), dp-&gt;d_name, &amp;fileStat, 0)
  • 嘿,我该怎么办?
猜你喜欢
  • 1970-01-01
  • 2021-08-29
  • 2014-07-16
  • 2012-04-23
  • 2010-11-10
  • 2017-01-14
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
相关资源
最近更新 更多