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.
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.
expect()
we specify an error message if the file is not present.try_into()
method to cast the u64
returned by len()
into a usize
.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
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.