Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 1.31 KB

read-file.zh.md

File metadata and controls

35 lines (26 loc) · 1.31 KB

从文件中,读取字符串行

[![std-badge]][std] [![cat-filesystem-badge]][cat-filesystem]

将一份三行的消息写入文件,然后由BufRead::lines,返回Lines迭代器,用来一次读取一行。 File实现了Read,也就是提供BufReader trait。File::create会打开一个File,用于写入(文件),而File::open用来读取。

use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error};

fn main() -> Result<(), Error> {
    let path = "lines.txt";

    let mut output = File::create(path)?;
    write!(output, "Rust\n💖\nFun")?;

    let input = File::open(path)?;
    let buffered = BufReader::new(input);

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

    Ok(())
}