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