How to combine reading a file line by line and repeating each character in each line?

I started with this code that just read every line in the file and works well:

use std::io::{BufRead, BufReader}; use std::fs::File; fn main() { let file = File::open("chry.fa").expect("cannot open file"); let file = BufReader::new(file); for line in file.lines() { print!("{}", line.unwrap()); } } 

... but then I also tried to iterate over each character in each line, something like this:

 use std::io::{BufRead, BufReader}; use std::fs::File; fn main() { let file = File::open("chry.fa").expect("cannot open file"); let file = BufReader::new(file); for line in file.lines() { for c in line.chars() { print!("{}", c.unwrap()); } } } 

... but it turns out that this very inner loop is wrong. The following error message appears:

 error[E0599]: no method named `chars` found for type `std::result::Result<std::string::String, std::io::Error>` in the current scope --> src/main.rs:8:23 | 8 | for c in line.chars() { | ^^^^^ 
+6
source share
1 answer

You need to handle the potential error that may occur with each I / O operation represented by io::Result , which may contain either the requested data or an error. There are various ways to handle errors.

One way is to simply ignore them and read any data that we can get.

The code shows how to do this:

 use std::io::{BufRead, BufReader}; use std::fs::File; fn main() { let file = File::open("chry.fa").expect("cannot open file"); let file = BufReader::new(file); for line in file.lines().filter_map(|result| result.ok()) { for c in line.chars() { print!("{}", c); } } } 

Key points: file.lines() is an iterator that gives io::Result . In filter_map we convert io::Result to Option and filter any occurrences of None . Then we leave only simple strings (i.e. Strings).

+13
source

Source: https://habr.com/ru/post/973449/


All Articles