I need to get the progress percent of copying a file which is currently just copying the file content into a fixed size buffer 1024
. To further improve the user experience I would like to print the progress of file copy operation, but I couldn't. This is what I've tried so far
use std::io::{Read, Write};
use std::fs::File;
fn write_to_file<R: Read, W: Write>(mut reader: R, mut writer: W) {
let mut buf = vec![0; 1024];
let mut bytes_read = buf.capacity();
while bytes_read > 0 {
bytes_read = reader.read(&mut buf).expect("failed to read from the file");
if bytes_read > 0 {
writer.write_all(&buf[..bytes_read]).expect("failed to write to the file");
}
// print the progress of copying
// println!("{}% completed", progress);
}
writer.flush().expect("failed to flush the writer");
}
fn main() {
let src_file = File::open("~/a.txt").expect("unable to open the file");
let dst_file = File::create("~/b.txt").expect("unable to create the file");
write_to_file(src_file, dst_file);
}