Created
January 1, 2019 09:54
-
-
Save krishnakumar4a4/dd14796c7594f866b589b082d2a53d57 to your computer and use it in GitHub Desktop.
recursively read files in a directory [Rust]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs; | |
use std::path::Path; | |
extern crate regex; | |
use regex::Regex; | |
fn main() { | |
get_files(local_index_file_path, vec!["^*.caidx$".to_owned(), "^*.caibx$".to_owned()]); | |
get_files(local_chunks_file_path, vec!["^*.cacnk$".to_owned()]); | |
} | |
// Print file names with specific extension, recursively | |
fn get_files(path: String, formats: Vec<String>) { | |
let mut files: Vec<String> = Vec::new(); | |
let mut rexps: Vec<Regex> = Vec::new(); | |
for format in formats { | |
rexps.push(Regex::new(&format).unwrap()); | |
} | |
read_dir_recursive(path.to_owned(), &mut files, rexps.clone()); | |
for name in files.iter() { | |
println!("File-> {}", name); | |
} | |
} | |
// Read file names of specific extension, recursively in all dirs | |
fn read_dir_recursive(path: String, files: &mut Vec<String>, rexps: Vec<Regex>) { | |
if Path::new(&path).is_dir() { | |
for entry in fs::read_dir(&path).unwrap() { | |
let dir = entry.unwrap(); | |
read_dir_recursive(dir.path().into_os_string().into_string().unwrap().to_owned(), files, rexps.clone()); | |
} | |
} else { | |
for rexp in rexps.iter() { | |
if rexp.is_match(&path) { | |
println!("file-> {}", path); | |
files.push(path.to_owned()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment