Calculate MD5 of a file in Rustrust/calc-md5-of-fileAn example of using md5 and file to calculate MD5 of a file in stream
1use md5::Context;
2use std::path::Path;
3use std::{fs, io};
4
5pub fn calculate_md5(file_path: &Path) -> io::Result<String> {
6 let file = fs::File::open(file_path)?;
7 let mut context = Context::new();
8 let mut buffer = [0; 4096]; // buffer size: 4KB
9
10 let mut reader = io::BufReader::new(file);
11 loop {
12 let bytes_read = reader.read(&mut buffer)?;
13 if bytes_read == 0 {
14 break;
15 }
16 context.consume(&buffer[..bytes_read]);
17 }
18
19 let result = context.compute();
20 Ok(format!("{:x}", result))
21}Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.