获取目录的大小(不是它的内容)

Get the size of a directory (not its content)

(请在驳回此问题之前阅读完整问题)

在 C++ 中,我们可以通过 运行 std::filesystem::file_size(PATH); 获取常规文件的文件大小,但此函数不适用于目录,这是我的问题。 我处于需要知道目录“inode”大小的情况,在(大多数)linux 系统中,目录的标准大小为 4kB 或块大小:

$:~/tmp/test$ mkdir ex
$:~/tmp/test$ ls -l
total 4
drwxrwxr-x 2 secret secret 4096 Oct 15 08:43 ex

这些 4kB 包含 space 用于在该目录中具有文件的“列表”。 但是,如果目录中的文件数量变得非常大,则文件夹的大小可能会增加(这就是我所在的位置)。 我需要能够跟踪这种增长。 所以我的问题是,除了从 C++ 调用 ls -ldu 之外,是否有一种 C++ 本地方法来获取目录的大小? 我知道它不适用于 std::filesystem::file_size(path) 的原因是文件系统以不同的方式表示目录。

https://en.cppreference.com/w/cpp/filesystem/file_size

For a regular file p, returns the size determined as if by reading the st_size member of the structure obtained by POSIX stat (symlinks are followed)

The result of attempting to determine the size of a directory (as well as any other file that is not a regular file or a symlink) is implementation-defined.

目录上的

file_size 在某些实现中可能实际上有效,但我猜你的不行。似乎没有纯 C++ 替代方案,但您可以自己调用 POSIX stat 函数。这确实适用于目录并报告你想要的数字。