W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
ch12-02-reading-a-file.md
commit 0f87daf683ae3de3cb725faecb11b7e7e89f0e5a
現(xiàn)在我們要增加讀取由 filename
命令行參數(shù)指定的文件的功能。首先,需要一個用來測試的示例文件:用來確保 minigrep
正常工作的最好的文件是擁有多行少量文本且有一些重復(fù)單詞的文件。示例 12-3 是一首艾米莉·狄金森(Emily Dickinson)的詩,它正適合這個工作!在項目根目錄創(chuàng)建一個文件 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!
示例 12-3:艾米莉·狄金森的詩 “I’m nobody! Who are you?”,一個好的測試用例
創(chuàng)建完這個文件之后,修改 src/main.rs 并增加如示例 12-4 所示的打開文件的代碼:
文件名: src/main.rs
use std::env;
use std::fs;
fn main() {
// --snip--
println!("In file {}", filename);
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
println!("With text:\n{}", contents);
}
示例 12-4:讀取第二個參數(shù)所指定的文件內(nèi)容
首先,我們增加了一個 use
語句來引入標(biāo)準(zhǔn)庫中的相關(guān)部分:我們需要 std::fs
來處理文件。
在 main
中新增了一行語句:fs::read_to_string
接受 filename
,打開文件,接著返回包含其內(nèi)容的 Result<String>
。
在這些代碼之后,我們再次增加了臨時的 println!
打印出讀取文件之后 contents
的值,這樣就可以檢查目前為止的程序能否工作。
嘗試運行這些代碼,隨意指定一個字符串作為第一個命令行參數(shù)(因為還未實現(xiàn)搜索功能的部分)而將 poem.txt 文件將作為第二個參數(shù):
$ cargo run the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [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!
好的!代碼讀取并打印出了文件的內(nèi)容。雖然它還有一些瑕疵:main
函數(shù)有著多個職能,通常函數(shù)只負(fù)責(zé)一個功能的話會更簡潔并易于維護。另一個問題是沒有盡可能的處理錯誤。雖然我們的程序還很小,這些瑕疵并不是什么大問題,不過隨著程序功能的豐富,將會越來越難以用簡單的方法修復(fù)他們。在開發(fā)程序時,及早開始重構(gòu)是一個最佳實踐,因為重構(gòu)少量代碼時要容易的多,所以讓我們現(xiàn)在就開始吧。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: