Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

open

open 関数は、ファイルを読み取り専用モードで開くために使用できます。

File はリソースであるファイルディスクリプタを所有し、drop されたときにファイルを閉じる処理を行います。

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // 目的のファイルへのパスを作成する
    let path = Path::new("hello.txt");
    let display = path.display();

    // パスを読み取り専用モードで開き、`io::Result<File>` を返す
    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why),
        Ok(file) => file,
    };

    // ファイルの内容を文字列に読み込み、`io::Result<usize>` を返す
    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),
    }

    // `file` がスコープを外れ、"hello.txt" ファイルが閉じられる
}

期待される成功時の出力は次のとおりです。

$ echo "Hello World!" > hello.txt
$ rustc open.rs && ./open
hello.txt contains:
Hello World!

(前の例をさまざまな失敗条件でテストすることをお勧めします。 たとえば、hello.txt が存在しない場合や、hello.txt が読み取り可能でない場合などです。)