파일 읽기

파일 읽기

이제 file_path 인자에 지정된 파일을 읽는 기능을 추가할게요. 먼저 테스트에 쓸 샘플 파일이 필요해요. 여러 줄로 된 짧은 텍스트에 단어 몇 개가 반복되는 파일을 쓰면 좋겠죠. Listing 12-3에 있는 에밀리 디킨슨(Emily Dickinson)의 시가 딱 좋아요! 프로젝트 루트에 poem.txt라는 파일을 만들고, "I'm Nobody! Who are you?" 시를 입력합니다.

파일명: poem.txt

I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

Listing 12-3: 에밀리 디킨슨의 시는 좋은 테스트 케이스가 돼요

텍스트가 준비됐으니 src/main.rs를 수정해서 파일을 읽는 코드를 추가합니다. Listing 12-4와 같아요.

파일명: src/main.rs

use std::env;
use std::fs;

fn main() {
    // --snip--
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let file_path = &args[2];

    println!("Searching for {query}");
    println!("In file {file_path}");

    let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

Listing 12-4: 두 번째 인자가 지정한 파일의 내용 읽기

먼저 use 문으로 표준 라이브러리의 관련 부분을 불러옵니다. 파일을 다루려면 std::fs가 필요해요.

main 안의 새 문장인 fs::read_to_stringfile_path를 받아 그 파일을 열고, 파일의 내용을 담은 std::io::Result<String> 타입의 값을 반환합니다.

그 다음에는 파일을 읽은 뒤 contents 값을 출력하는 임시 println! 문을 또 추가해서, 지금까지 프로그램이 동작하는지 확인할 수 있게 합니다.

첫 번째 명령줄 인자는 아무 문자열이나(아직 검색 기능을 구현하지 않았으니) 넣고, 두 번째 인자에는 poem.txt 파일을 넣어 실행해 볼게요:

$ cargo run -- the poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

좋아요! 코드가 파일을 읽은 뒤 그 내용을 출력했어요. 그런데 이 코드에는 단점이 몇 가지 있어요. 지금 main 함수가 여러 책임을 지고 있는데, 보통 함수는 각각 하나의 아이디어만 담당할 때 더 명확하고 유지보수하기 쉬워요. 또 하나는 오류 처리가 충분하지 않다는 점입니다. 프로그램이 아직 작아서 이런 단점이 큰 문제는 아니지만, 프로그램이 커지면 깔끔하게 고치기가 더 어려워져요. 프로그램을 개발할 때 리팩터링을 일찍 시작하는 건 좋은 습관인데, 코드 양이 적을 때 고치는 게 훨씬 쉽거든요. 그 작업을 다음에 해볼게요.

출처: The Rust Book

더 알아보기 (Learn more)