Lars Kakavandi-Nielsen
Lars Kakavandi-Nielsen

Reputation: 2198

Get the size of a directory (not its content)

(please before dismissing this as already answered, read the full question)

In C++ we can get the file size of a regular file by running std::filesystem::file_size(PATH); But this function does not work on directories, which is my problem. I am in a situation where I need to know the size of directory "inode", in (most) linux systems the standard size of a directory is 4kB or block size:

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

These 4kB inlcudes space for having a "list" of the file in that directory. But if the number of files in the directory becomes significantly large, the size of the folder can increase (which is where I am). I need to be able to track this increase. So my question is that besides calling ls -l or du from C++ is there a C++-native way of getting the size of the directory? I am aware that the reason it does not work with std::filesystem::file_size(path) is due file systems different ways of representing directories.

Upvotes: 2

Views: 362

Answers (1)

user14215102
user14215102

Reputation:

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 on a directory may actually work in some implementations, but I guess that yours doesn't. There doesn't appear to be a pure C++ alterantive, but you can call the POSIX stat function yourself. That does work on directories and reports the number you want.

Upvotes: 1

Related Questions