get size of a file or folder in rust

To get the size of a file in Rust, we can use the std::fs::metadata function. This function returns a std::fs::Metadata struct, which gives us information about a file's metadata, such as its size.

Here's an example code that demonstrates how to get the size of a file in Rust:

main.rs
use std::fs;

fn main() {
    let filename = "example.txt";
    let metadata = fs::metadata(filename).unwrap();
    let size = metadata.len();
    println!("File size: {} bytes", size);
}
188 chars
9 lines

This code will output the size of the example.txt file in bytes.

To get the size of a folder, we need to recursively iterate over all files and subfolders inside the folder and sum their sizes. Here's an example:

main.rs
use std::fs;

fn get_folder_size(folder: &str) -> u64 {
    let mut size = 0;
    for entry in fs::read_dir(folder).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            size += get_folder_size(path.to_str().unwrap());
        } else {
            size += fs::metadata(path).unwrap().len();
        }
    }
    size
}

fn main() {
    let foldername = "example_folder";
    let size = get_folder_size(foldername);
    println!("Folder size: {} bytes", size);
}
499 chars
21 lines

This code will output the size of the example_folder folder in bytes.

related categories

gistlibby LogSnag