Home
Rust
File Size (fs metadata)
Updated Mar 3, 2025
Dot Net Perls
File size. How can we get the size in bytes of a file in Rust? It is possible to read the file into a vector, and get the length of the vector, but this is inefficient.
Instead, we can use the filesystem metadata, which is part of the fs module in the standard library. Then we just access the len() function.
File modified Date
Example. Here we see a special method, get_file_length, that accesses the metadata struct for a file. If many parts of the metadata are needed, the same metadata struct could be used.
Part 1 We call metadata with a file name argument. With expect() we specify an error message if the file is not present.
Part 2 We use the try_into() method to cast the u64 returned by len() into a usize.
usize
Part 3 We call our special function (get_file_length). If the file is present, it returns a usize indicating the byte count of the file.
use std::fs; pub fn get_file_length(file: &str) -> usize { // Part 1: get metadata for file. let metadata = fs::metadata(file).expect("Need metadata"); // Part 2: get length of file from metadata, and convert to usize. metadata.len().try_into().unwrap() } fn main() { // Part 3: call function that gets file length. let result = get_file_length("Cargo.toml"); println!("FILE LENGTH: {}", result); }
FILE LENGTH: 81
Summary. With the fs module, we can access metadata about a file. This is stored separately on the filesystem, so we do not need to process the file in its entirety.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 3, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen