Io 如何正确读取文本文件?
锈-0.11 新手问题:Io 如何正确读取文本文件?,io,rust,Io,Rust,锈-0.11 新手问题: fn main() { use std::io::File; use std::str;
fn main() {
use std::io::File;
use std::str;
let unwrapped_data = match File::open(&Path::new("/proc/net/dev")).read_to_end() {
Ok(byte_mas) => byte_mas,
Err(why) => fail!("couldn't open: {}", why.desc),
};
println!("{}", str::from_utf8_owned(unwrapped_data));
}
输出:
./netstat
Ok(Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 1534066 17270 0 0 0 0 0 0 1534066 17270 0 0 0 0 0 0
enp2s0: 251195693 592728 0 17723 0 0 0 0 43664332 107083 0 0 0 0 0 0
)
如何在没有“Ok()”的情况下阅读?
细节
细节
细节
细节
细节
细节
细节
详细信息有签名:
pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>>
代码之所以“有效”是因为Result
实现了Show
特性(这是{}
格式化程序调用的),因此可以直接打印
(您实际上可以通过缩写此过程,它读取整个读卡器并检查其内部是否为UTF-8。)(您的意思是让“详细信息”重复多次而不提供更多详细信息吗?)
match str::from_utf8_owned(unwrapped_data) {
Ok(s) => println!("{}", s),
Err(_) => fail!("file was not valid UTF-8")
}