Làm sao để đọc file trong Rust một cách an toàn và xử lý lỗi tốt?
Làm sao để đọc file trong Rust một cách an toàn và xử lý lỗi tốt?
```rust
use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn read_file(path: &str) -> io::Result<()> {
let file = File::open(path);
match file {
Ok(file) => {
let reader = BufReader::new(file);
for line in reader.lines() {
match line {
Ok(content) => {
// **Xử lý nội dung của dòng**
println!("{}", content);
}
Err(e) => {
// **Xử lý lỗi khi đọc dòng**
eprintln!("Error reading line: {}", e);
}
}
}
}
...
middle