Rust 檔案操作 read_to_string和read - 讀取檔案
最近有一個想要做的小東西
會先用到操作文檔
這篇文章先稍微介紹一下兩個讀取的方法
分別是read_to_string、read
而讀取文件總要有個文件讓我讀
因此在目錄底下創建一個poem.txt
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!
std::fs[1]
文件操作的放在std::fs底下
fs為filesystem
這個包常用於操作系統文件
常見的包括create、read、write等等
當想操作文件時都必須
use std::fs;
read_to_string[2]
read_to_string為將文件內容放入字串中
文件這樣解釋
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>
輸入一個路徑,最後輸出一個Result
看一個範例打法
use std::fs;
fn main() {
let file_path = "poem.txt";
let contents = fs::read_to_string(file_path)
.expect("Should have been able to read the file");
println!("{}", contents);
}
先透過file_path指定我的路徑
路徑也可以使用絕對路徑
這邊先使用相對路徑
contents為檔案的內容,並且將檔案內容轉為string
如果讀不到檔案則會直接panic,並顯示
thread 'main' panicked at 'Should have been able to read the file: Os
{ code: 2, kind: NotFound, message: "系統找不到指定的檔案。" }', src\main.rs:6:10
stack backtrace:
read[3]
read為將檔案內容轉vector
文件這樣解釋
pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>>
輸入一個路徑,輸出為result
並且如果成功內容為Vec<u8>
u8意思為會把每個ASCII碼輸出
看個例子
use std::fs;
fn main() {
let file_path = "D:\\Blog\\rust\\poem.txt";
let contents = fs::read(file_path)
.expect("Should have been able to read the file");
println!("{:?}", contents);
}
32, 121, 111, 117, 63, 13, 10, 65, 114, 101, 32, 121, 111, 117, 32, 110, 111, 98, 111,
100, 121, 44, 32, 116, 111, 111, 63, 13, 10, 84, 104, 101, 110, 32, 116, 104, 101,
114, 101, 39, 115, 32, 97, 32, 112, 97, 105, 114, 32, 111, 102, 32, 117, 115, 32, 45,
32, 100, 111, 110, 39, 116, 32, 116, 101, 108, 108, 33, 13, 10, 84, 104, 101, 121,
39, 100, 32, 98, 97, 110, 105, 115, 104, 32, 117, 115, 44, 32, 121, 111, 117, 32, 107,
110, 111, 119, 46, 13, 10, 13, 10, 72, 111, 119, 32, 100, 114, 101, 97, 114, 121, 32,
116, 111, 32, 98, 101, 32, 115, 111, 109, 101, 98, 111, 100, 121, 33, 13, 10, 72,
111, 119, 32, 112, 117, 98, 108, 105, 99, 44, 32, 108, 105, 107, 101, 32, 97, 32, 102,
114, 111, 103, 13, 10, 84, 111, 32, 116, 101, 108, 108, 32, 121, 111, 117, 114, 32,
110, 97, 109, 101, 32, 116, 104, 101, 32, 108, 105, 118, 101, 108, 111, 110, 103, 32,
100, 97, 121, 13, 10, 84, 111, 32, 97, 110, 32, 97, 100, 109, 105, 114, 105, 110, 103,
32, 98, 111, 103, 33, 13, 10]
這次使用絕對路徑
使用絕對路徑要兩個\\才表示一個\
如果只使用一個\會跟後面英文組合
例如\n就組合成換行
而輸出可以看到是vector
裡面都是數字,每個數字表示一個字
拿個維基百科的ASCII[5]來對照一下
可以翻譯成詩中內容
參考資料
[1] https://doc.rust-lang.org/std/fs/
[2] https://doc.rust-lang.org/std/fs/fn.read_to_string.html
[3] https://doc.rust-lang.org/std/fs/fn.read.html
[4] https://tw.crystal-lang.org/docs/syntax_and_semantics/literals/string.html
0 comments:
張貼留言