How to search a file content and process it?

I have a text file with multiple lines (around 3000 lines). I wanted to populate my multiple structs based on the file content. Hence, I read the file and stored it as a Vec<String>. Then I find the position of the keyword,

use std::fs;
use std::io::{BufReader, Read, BufRead};    

pub fn reader(path: &str) {

    let f = fs::File::open(path).expect("no file found");
    let br = BufReader::new(f);
    let mut lines: Vec<String> = br.lines().collect::<Result<_, _>>().unwrap();

    let keyword1_iter = seek(lines, "key1");
    let a = keyword1_iter.next();
    let b = keyword1_iter.next();

    let keyword2_iter = seek(lines, "key0");
    let c = keyword2_iter.next();
    let d = keyword2_iter.next();
    let e = keyword2_iter.next();
   
   // And so on.

}

pub fn seek(lines: Vec<String>, keyword: &str) -> impl Iterator<Item = String>{
    let a = lines.iter();
    let keyword_position = a.position(|line| line.starts_with(keyword)).unwrap();
    let _ = a.nth(keyword_position);
    return a;
}

I am getting compiler error. Also, I am not sure if this is the right approach (optimised). Can you help me?

My text file is something like below,

key0
aa
ab xy
ac
key1
ba
bb
bc
bd
be
key2
ca mn
cb

The nth and position functions consume the iterator, so you can't use it after calling either.

@alice - Thanks :slight_smile: I figured something like below will work,

let mut lines = br.lines().filter_map(Result::ok).map(|line| line.split_whitespace()); //.map(|line| line.unwrap()).collect(); // collect::<Result<_, _>>().unwrap();

    let key_position = lines.position(|line| line.any("key0")).unwrap();
    println!("{:?}", lines.next().unwrap());
    println!("{:?}", lines.next().unwrap());

However, I am not able to use split_whitespace. Compiler complains cannot return reference to temporary value

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.