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

อ่านไฟล์

ตอนนี้เราจะเพิ่ม functionality เพื่ออ่านไฟล์ที่ระบุในอาร์กิวเมนต์ file_path ก่อนอื่น เราต้องการไฟล์ตัวอย่างเพื่อทดสอบ — เราจะใช้ไฟล์ ที่มี text จำนวนเล็กน้อยในหลายบรรทัดพร้อมคำที่ซ้ำกัน Listing 12-3 มี บทกวีของ Emily Dickinson ที่จะทำงานได้ดี! สร้างไฟล์ชื่อ poem.txt ที่ ระดับ root ของโปรเจกต์ของคุณ และใส่บทกวี “I’m Nobody! Who are you?”

Filename: 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: บทกวีของ Emily Dickinson เป็น test case ที่ดี

เมื่อมี text แล้ว แก้ไข src/main.rs และเพิ่มโค้ดเพื่ออ่านไฟล์ ดังที่ แสดงใน Listing 12-4

Filename: 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: อ่านเนื้อหาของไฟล์ที่ระบุโดยอาร์กิวเมนต์ที่สอง

ก่อนอื่น เรานำส่วนที่เกี่ยวข้องของ standard library เข้ามาด้วย statement use — เราต้องการ std::fs เพื่อจัดการไฟล์

ใน main statement ใหม่ fs::read_to_string รับ file_path, เปิด ไฟล์นั้น และ return ค่า type std::io::Result<String> ที่บรรจุเนื้อหา ของไฟล์

หลังจากนั้น เราเพิ่ม statement println! ชั่วคราวอีกครั้งที่ print ค่าของ contents หลังจากอ่านไฟล์ เพื่อให้เราตรวจสอบได้ว่าโปรแกรมทำงาน จนถึงจุดนี้

มารันโค้ดนี้ด้วย string ใด ๆ เป็นอาร์กิวเมนต์ command line แรก (เพราะ เรายังไม่ได้ implement ส่วนค้นหา) และไฟล์ 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!

ดี! โค้ดอ่านและ print เนื้อหาของไฟล์ แต่โค้ดมีข้อบกพร่องอยู่บ้าง ตอน นี้ฟังก์ชัน main มีหลายความรับผิดชอบ — โดยทั่วไป ฟังก์ชันชัดเจนและ ดูแลรักษาง่ายขึ้นถ้าแต่ละฟังก์ชันรับผิดชอบเพียงหนึ่งความคิด ปัญหาอีก อย่างคือเราไม่ได้จัดการ error ดีเท่าที่ทำได้ โปรแกรมยังเล็ก ดังนั้น ข้อบกพร่องเหล่านี้ไม่เป็นปัญหาใหญ่ แต่เมื่อโปรแกรมเติบโต มันจะยากขึ้น ที่จะแก้พวกมันให้สะอาด เป็นการปฏิบัติที่ดีที่จะเริ่ม refactor แต่ เนิ่น ๆ เมื่อพัฒนาโปรแกรม เพราะ refactor โค้ดจำนวนน้อยง่ายกว่ามาก เราจะทำเช่นนั้นต่อไป