Skip to content

Instantly share code, notes, and snippets.

@SnejUgal
Last active February 22, 2021 17:21
Show Gist options
  • Save SnejUgal/105789d9ebf38b3f89e3c9c9b0ec3542 to your computer and use it in GitHub Desktop.
Save SnejUgal/105789d9ebf38b3f89e3c9c9b0ec3542 to your computer and use it in GitHub Desktop.
Find the position of the last non-zero byte in a file
use std::io::{prelude::*, SeekFrom};
const CHUNK: usize = 512 * 1024 * 1024;
fn main() {
let path = std::env::args_os().nth(1).unwrap();
let mut file = std::fs::File::open(path).unwrap();
let mut position = file.seek(SeekFrom::End(-(CHUNK as i64))).unwrap();
let mut buffer = vec![0; CHUNK];
loop {
file.read_exact(&mut buffer).unwrap();
if let Some(index) = buffer.iter().rposition(|&byte| byte != 0) {
println!("{}", position + index as u64);
return;
}
print!(".");
std::io::stdout().flush().unwrap();
position = file.seek(SeekFrom::Current(-(CHUNK as i64 * 2))).unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment