使用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
我喜欢你有记录(遍历order..performance)的额外条件。 +1 – eeerahul
关于详尽处理面试问题的原型治疗,请参阅[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