如何在Linux中以编程方式获取dir的大小?

5 c linux size dir

我想通过C程序获取linux中特定目录的确切大小.我尝试使用statfs(path,struct statfs&)但它没有给出确切的大小.我也尝试过stat()但是对于任何一个dir,它返回大小为4096!

请建议我通过"du -sh dirPath"命令得到dir的确切大小的方式.

另外,我不想通过系统()使用du.

提前致谢.

Dav*_*vis 9

典型解决方案

如果你想要一个目录的大小,类似于du的方式,创建一个递归函数.迭代地解决问题是可能的,但解决方案有助于递归.

信息

这是一个帮助您入门的链接:

http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/lecture.html

搜索

使用'stat c program recursive directory size'搜索Google

直接来自Jim Plank的网站,作为一个例子来帮助您入门.

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>

main()
{
  DIR *d;
  struct dirent *de;
  struct stat buf;
  int exists;
  int total_size;

  d = opendir(".");
  if (d == NULL) {
    perror("prsize");
    exit(1);
  }

  total_size = 0;

  for (de = readdir(d); de != NULL; de = readdir(d)) {
    exists = stat(de->d_name, &buf);
    if (exists < 0) {
      fprintf(stderr, "Couldn't stat %s\n", de->d_name);
    } else {
      total_size += buf.st_size;
    }
  }
  closedir(d);
  printf("%d\n", total_size);
}
Run Code Online (Sandbox Code Playgroud)


Byr*_*ock 5

您需要 stat() 当前目录和子目录中的所有文件并将它们相加。

考虑为此使用递归算法。