簡體   English   中英

如何從目錄中找出文件的大小

[英]How to find out the size of the files from a directory

所以我有一段代碼,它通過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;
    }
}

dp->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 );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM