2013-04-22 93 views
-1

我必須做ls -l函數。我的問題是從ls -l中找到總值。這是我如何做到的。C,總共來自unix ls函數

if (l_option) { 
    struct stat s; 
    stat(dir_name, &s); 
    printf("total %jd\n", (intmax_t)s.st_size/512); 
} 

我相信,我的解決方案是正確的定義,那就是: 「對於每個列出的目錄,前言中的文件與線 `總塊」,其中模塊是所有的總磁盤分配 該目錄中的文件,塊大小目前默認爲1024 字節「(info ls)但我的功能與真正的ls不同。

例如:

>ls -l 
>total 60 

...並在同一目錄下:

>./ls -l 
>total 8 

如果我寫:

>stat . 
>File: `.' 
>Size: 4096   Blocks: 8   IO Block: 4096 directory 
>... 
+4

目錄大小!=它裏面的文件大小!您必須通過目錄,獲取所有文件的統計數據並總結其大小。 – 2013-04-22 16:51:58

+0

謝謝,好像我的文件系統的概念是完全錯誤的。 – mzdravkov 2013-04-22 16:54:45

回答

0

我固定它:

n = scandir(path, &namelist, filter, alphasort); 

if (l_option) { // flag if -l is given 
    while (i < n) { 
    char* temp = (char *) malloc(sizeof(path)+sizeof(namelist[i]->d_name)); 
    strcpy(temp, path); //copy path to temp 
    stat(strcat(temp, namelist[i]->d_name), &s); // we pass path to + name of file 
    total += s.st_blocks; 
    free(temp); 
    free(namelist[i++]); // optimization rules! 
    } 
    free(namelist); 
    printf("total %d\n", total/2); 
} 

所以基本上,我讓包含DIR_NAME +文件名新的字符數組,然後我得到的統計結構,用它來查找總。

0

您應該使用執行opendir/readdir的/ closedir 。

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

int main(void) 
{ 
    DIR   *d; 
    struct dirent *dir; 
    d = opendir("."); 
    if (d) 
    { 
    while ((dir = readdir(d)) != NULL) 
    { 
     count++; 
    } 

    closedir(d); 
    } 
    printf("total %jd\n",count); 
    return(0); 
} 
+0

您的答案缺少計算總文件大小,我相信這是問題所在。 – hyde 2013-08-27 14:18:27