其他分享
首页 > 其他分享> > 【Rust】打开文件

【Rust】打开文件

作者:互联网

环境

概念

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

示例

main.rs

use std::fs::File;
use std::io::Read;
use std::path::Path;

fn main() {
    let path = Path::new("hello.txt");
    let display = path.display();

    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why),
        Ok(file) => file,
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("couldn't read {}: {}", display, why),
        Ok(_) => print!("{} contains:\n{}", display, s),
    }
}

总结

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

附录

标签:std,文件,why,let,file,path,打开,display,Rust
来源: https://www.cnblogs.com/jiangbo44/p/15744071.html