pesho hristov
pesho hristov

Reputation: 2060

How to check directory size?

Is there a way to check the size of the folder with Rust?

I didn't see such method mentioned. I can do it via invoking a shell command but I prefer to avoid this if possible.

Upvotes: 9

Views: 6014

Answers (3)

stuart
stuart

Reputation: 2253

crate fs_extra seems to work well for me https://docs.rs/fs_extra/1.2.0/fs_extra/dir/fn.get_size.html

Cargo.toml

[dependencies]
fs_extra = "1.2.0"

code

extern crate fs_extra;
use fs_extra::dir::get_size;

fn main(){
  let folder_size = get_size("dir").unwrap();
  println!("{}", folder_size); // print directory sile in bytes
}

Upvotes: 10

Boiethios
Boiethios

Reputation: 42759

Either you use a crate, or you calculate it by hand, with something like that (recursive solution):

use std::{fs, io, path::PathBuf};

fn dir_size(path: impl Into<PathBuf>) -> io::Result<u64> {
    fn dir_size(mut dir: fs::ReadDir) -> io::Result<u64> {
        dir.try_fold(0, |acc, file| {
            let file = file?;
            let size = match file.metadata()? {
                data if data.is_dir() => dir_size(fs::read_dir(file.path())?)?,
                data => data.len(),
            };
            Ok(acc + size)
        })
    }

    dir_size(fs::read_dir(path.into())?)
}

fn main() -> io::Result<()> {
    println!("{}", dir_size(".")?);

    Ok(())
}

Upvotes: 4

Masklinn
Masklinn

Reputation: 42292

Could you explain what you mean more specifically? Do you just want to get a du-like information (recursively sum the size of each file)?

In that case you probably want to use std::fs::read_dir, iterate on the entries, sum the sizes (via metadata) of the non-directories, and recurse into directories.

I'm pretty sure there is no builtin du, I don't think there even is a builtin recursive directory walker (hence walkdir)

Upvotes: 4

Related Questions