toti
toti

Reputation: 335

Reading all file contents in current directory to a vector

I want to read all the files in the current directory.

Here's my progress:

use std::fs;

fn main() {
    let files = fs::read_dir(".").unwrap();
    files
        .filter_map(Result::ok)
        .filter(|d| if let Some(e) = d.path().extension() { e == "txt" } else {false})
        .for_each(|f| println!("{:?}", f));
}

Here I got a little lost, how can I read all file contents? Should I add them to a growing Vec in the for_each block? if so then how?

Upvotes: 0

Views: 803

Answers (1)

pigeonhands
pigeonhands

Reputation: 3424

If you want a single vec with all files bytes in one you can use

let target_ext = OsString::from("txt");
let files = fs::read_dir(".").unwrap();
let file_bytes : Vec<u8> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .flat_map(|path| fs::read(path).expect("Failed to read"))
    .collect();

if you want a vec that contains each file's content separately, change flat_map to a map and it will return a Vec<Vec<u8>>

let file_bytes : Vec<Vec<u8>> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .map(|path| fs::read(path).expect("Failed to read"))
    .collect();

Upvotes: 1

Related Questions