📝

0007 file-open

に公開

std::path::Pathとか使う

use std::{fs::File, io::Read, 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),
    }
}
[package]
name = "file-open"
version = "0.1.0"
edition = "2024"

[dependencies]

Discussion