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!("{}를 열 수 없습니다: {}", display, why),
        Ok(file) => file,
    };

    // 파일 내용을 문자열로 읽어옵니다. `io::Result<usize>`를 반환합니다
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("{}를 읽을 수 없습니다: {}", display, why),
        Ok(_) => print!("{}의 내용:\n{}", display, s),
    }

    // `file`이 스코프를 벗어나고, "hello.txt" 파일이 닫힙니다
}

예상되는 성공적인 출력 결과는 다음과 같습니다:

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

(이전 예제를 hello.txt가 존재하지 않거나, 읽기 권한이 없는 등 다양한 실패 조건에서 테스트해 보시길 권장합니다.)