有沒有辦法獲得遞歸的子目錄的總大小?如何獲取C中子目錄的總大小?
例如:
Dir1
-- FileA.txt (90)
-- SubDir2 (4096)
---- FileB.txt (100)
---- FileC.txt (400)
當我試圖讓SubDir2的大小,它給了我4186預期的答案,我希望得到的是4596.
我的程序計算FILEA的大小而不是FileB和FileC。如何使它計數FileB和FileC?
首先,我必須使用這些標頭:
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
於是,我做了這個函數遞歸調用它:
static DIR *dir;
void goDir(char* argv[])
{
struct dirent *dit;
struct stat st;
int size = 0;
static int total_size = 0;
char filePath[NAME_MAX];
while ((dit = readdir(dir)) != NULL)
{
sprintf(filePath, "%s/%s", argv[1], dit->d_name); // To show correctly the size and name of files
lstat(filePath, &st);
// To skip . and ..
if ((strcmp(dit->d_name, ".") == 0) || (strcmp(dit->d_name, "..") == 0)) continue;
size = st.st_size;
if(S_ISDIR(st.st_mode))
{
goDir(argv); // For Recursivity
total_size += size;
printf("DIR\t");
printf("MODE: %lo\t", (unsigned long) st.st_mode);
printf("SIZE: %d\t", total_size);
printf("%s\n", dit->d_name);
}
else
{
total_size += size;
printf("FILES\t");
printf("MODE: %lo\t", (unsigned long) st.st_mode);
printf("SIZE: %d\t", size);
printf("%s\n", dit->d_name);
}
}
}
然後,我的主要程序:
int main (int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: Program <Directory>\n");
return 1;
}
if ((dir = opendir(argv[1])) == NULL) return 1;
goDir(argv);
closedir(dir);
return 0;
}
您目前無法顯示子目錄的總大小,因爲您只保留目前爲止所看到的所有項目的大小(您的靜態'total_size'變量)的總計大小。你想要做的是讓你的函數返回它檢查的目錄的總大小。 –