2011-10-06 47 views
2

我在思科采访中得到了这个问题:编写一个函数来查找目录的大小?查找一个目录的大小

以下是这种函数的伪代码,它遵循递归方法。请告诉我是否还有其他方法。

int directorySize(DirectoryHandle dh) 
{ 
    int size=0; 
    if (!dh) 
    { 
     DirectoryHandle dh1 = directoryOpen("Directory_path"); 
    } 
    else 
    { 
     dh1 = dh; 
    } 

    while (dh1) 
    { 
     if (TRUE=IsDirectory(dh1)) 
     { 
      size += directorysize(dh1); 
     } 
     else if (TRUE == IsFile(dh1)) 
     { 
      FileHandle fh = dh1; 
      while (EOF != fh) 
      { 
       size++; 
      } 
     } 
    } 
} 

回答

2

使用nftw的典型例子:

注意,因为面试问题去,他们可能会希望看到你想

  • 遍历顺序
  • 许可(无法访问子文件夹等。 )
  • 尺寸ondisk与表观尺寸
  • 符号链接,hardli nks(树外?重复计数)
  • 稀疏文件
  • 性能

下面的代码确实解决大多数问题,以务实的方式:

#define _XOPEN_SOURCE 500 
#include <ftw.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 

static uintmax_t total  = 0ul; 
static uintmax_t files  = 0ul; 
static uintmax_t directories = 0ul; 
static uintmax_t symlinks  = 0ul; 
static uintmax_t inaccessible = 0ul; 
static uintmax_t blocks512 = 0ul; 

static int 
display_info(const char *fpath, const struct stat *sb, 
      int tflag, struct FTW *ftwbuf) 
{ 
    switch(tflag) 
    { 
     case FTW_D: 
     case FTW_DP: directories++; break; 
     case FTW_NS: 
     case FTW_SL: 
     case FTW_SLN: symlinks++;  break; 
     case FTW_DNR: inaccessible++; break; 
     case FTW_F: files++;  break; 
    } 
    total += sb->st_size; 
    blocks512 += sb->st_blocks; 
    return 0; /* To tell nftw() to continue */ 
} 

int 
main(int argc, char *argv[]) 
{ 
    int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS; 

    if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags) == -1) 
    { 
     perror("nftw"); 
     exit(EXIT_FAILURE); 
    } 

    printf("Total size: %7jd\n", total); 
    printf("In %jd files and %jd directories (%jd symlinks and %jd inaccessible directories)\n", files, directories, symlinks, inaccessible); 
    printf("Size on disk %jd * 512b = %jd\n", blocks512, blocks512<<9); 

    exit(EXIT_SUCCESS); 
} 

此前发布为Fastest ways to get a directory Size and Size on disk。典型输出:

Total size: 28433001733 
In 878794 files and 87047 directories (73318 symlinks and 0 inaccessible directories) 
Size on disk 59942192 * 512b = 30690402304 
+0

我喜欢你有记录(遍历order..performance)的额外条件。 +1 – eeerahul

+0

关于详尽处理面试问题的原型治疗,请参阅[http://www.codinghorror.com/blog/2006/05/snappy-answers-to-stupid-programming-questions.html](http://www.codinghorror.com/blog/2006/05/snappy-答案到愚蠢的编程,questions.html) – sehe

1

也许增加了对大型文件集更多的空间和更好的子目录导航。

long DirectoryLength(DirectoryInfo dir) 
{ 
    long size = 0; 
    foreach (FileInfo file in dir.GetFiles()) 
     size += file.Length; 

    foreach (DirectoryInfo sub in dir.GetDirectories()) 
     size += DirectoryLength(sub); 

    return size; 
}