find the size of a directory in rust

To find the size of a directory in Rust, you can use the walkdir crate to recursively walk through the directory and add up the sizes of all files in the directory.

Here is an example function:

main.rs
extern crate walkdir;

use std::fs::File;
use std::io::{BufReader, Seek, SeekFrom};
use walkdir::{DirEntry, WalkDir};

fn get_directory_size(path: &str) -> u64 {
    let mut total_size: u64 = 0;

    for entry in WalkDir::new(path) {
        if let Ok(entry) = entry {
            if entry.file_type().is_file() {
                let file = File::open(entry.path()).unwrap();
                let metadata = file.metadata().unwrap();
                let file_size = metadata.len();
                total_size += file_size;
            }
        }
    }

    total_size
}
570 chars
23 lines

The get_directory_size function takes a path to a directory and returns the total size of all files in the directory (in bytes).

It uses WalkDir::new(path) to recursively walk through the directory and entry.file_type().is_file() to check if an entry is a file (and not a directory or other type of entry).

For each file entry, it opens the file, gets the file size from the file metadata, and adds it to the total size.

Note that the function does not account for the size of directories themselves, only the size of files within them. If you want to include the size of directories, you can modify the function to check for directory entries and add their size as well.

gistlibby LogSnag