其他分享
首页 > 其他分享> > 【Rust】按行读取

【Rust】按行读取

作者:互联网

环境

概念

参考:https://doc.rust-lang.org/stable/rust-by-example/std_misc/file/read_lines.html

示例

main.rs

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

fn main() {
    if let Ok(lines) = read_lines("src/main.rs") {
        lines.for_each(|line| {
            if let Ok(line) = line {
                println!("{}", line);
            }
        });
    }
}

fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
    P: AsRef<Path>,
{
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

总结

了解了 Rust 中读取文件中每一行内容的方法。

附录

标签:std,file,读取,lines,use,按行,io,line,Rust
来源: https://www.cnblogs.com/jiangbo44/p/15744078.html