Skip to content

Instantly share code, notes, and snippets.

@Ophirr33
Created November 30, 2017 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ophirr33/d9a5439a2a7c101c656086f2ef0c5ec6 to your computer and use it in GitHub Desktop.
Save Ophirr33/d9a5439a2a7c101c656086f2ef0c5ec6 to your computer and use it in GitHub Desktop.
Finds files made of only the null-byte
extern crate walkdir;
extern crate rayon;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::env::args;
use walkdir::{WalkDir, DirEntry, Result};
use rayon::prelude::*;
fn main() {
let mut args = args().skip(1);
let directory = args.next().expect("Usage: ./find-bad-files directory");
WalkDir::new(directory).into_iter().collect::<Vec<_>>().into_par_iter().for_each(bad_entry_res);
}
fn bad_entry(entry: DirEntry) {
if entry.file_type().is_file() {
match File::open(entry.path()) {
Err(e) => {
eprintln!("Error! Can't open file at {} due to {}", entry.path().display(), e);
},
Ok(file) => {
if BufReader::new(file).bytes().all(|b| b.expect("could not read byte") == 0) {
println!("{}", entry.path().display());
}
}
}
}
}
fn bad_entry_res(entry_res: Result<DirEntry>) {
match entry_res {
Ok(entry) => bad_entry(entry),
Err(err) => {
let path = err.path().unwrap_or(Path::new("")).display();
eprintln!("Error! Could not access entry for {}, ", path);
if let Some(inner) = err.io_error() {
match inner.kind() {
std::io::ErrorKind::InvalidData => {
eprint!(
"entry contains invalid data: {}", inner)
}
std::io::ErrorKind::PermissionDenied => {
eprint!("missing permission to read entry: {}", inner)
}
_ => {
eprint!("unexpected error occurred: {}", inner)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment