Rust 逐行读取txt文本内容

180it 2021-05-11 AM 420℃ 0条

demo1:

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("data.txt")?;
    let reader = BufReader::new(file);

    for line in reader.lines() {
        println!("{}", line?);
    }

    Ok(())
}

demo2:

use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;

fn main() {
    let f = File::open("./data.txt")
        .map_err(|err| err.to_string());

    if let Ok(data_file) = f {
        let reader = BufReader::new(data_file);
        for line in reader.lines() {
            println!("{}", line.unwrap());
        };                           
    }        
}

demo3:

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // Create a path to the desired file
    let path = Path::new("data.txt");
    let display = path.display();
    // Open the path in read-only mode, returns `io::Result<File>`
    let file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };
    let reader = BufReader::new(file);
    for line in reader.lines() {
        match line {
            Ok(line) => {
               
                    println!("{}", line)
               
            }
            Err(e) => println!("ERROR: {}", e),
        }
    }
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

Rust 逐行读取txt文本内容