內(nèi)容都是谷歌前兩個(gè)結(jié)果曾掂,我也不是謙虛领舰,只是普通的復(fù)制粘貼
std::fs::File::open
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// Create a path to the desired file
let path = Path::new("hello.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let mut file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display,
why.description()),
Ok(file) => file,
};
// Read the file contents into a string, returns `io::Result<usize>`
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("couldn't read {}: {}", display,
why.description()),
Ok(_) => print!("{} contains:\n{}", display, s),
}
// `file` goes out of scope, and the "hello.txt" file gets closed
}
最后一句話看的出來(lái)rust可真他媽安全,都不用close了,當(dāng)然因?yàn)檫@個(gè)特性寫別的語(yǔ)言的時(shí)候可能就會(huì)忘掉這碼事也不太好
復(fù)制于:
https://rustbyexample.com/std_misc/file/open.html
use std::env;
use std::fs::File;
use std::io::prelude::*;
fn main() {
// --snip--
println!("In file {}", filename);
let mut f = File::open(filename).expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
println!("With text:\n{}", contents);
}
跟上面丑丑的代碼相比号杏,官方書的代碼稍微漂亮點(diǎn),至少多用了個(gè)expect。盾致。主经。
復(fù)制于:
https://doc.rust-lang.org/book/second-edition/ch12-02-reading-a-file.html
trait std::io::Read
pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Result<[usize]>; //返回讀了多少個(gè)byte
unsafe fn initializer(&self) -> Initializer { ... }
fn read_to_end(&mut self, buf: &mut Vec<[u8]>) -> Result<usize> { ... } //全讀進(jìn)Vec
fn read_to_string(&mut self, buf: &mut String) -> Result<usize> { ... } //全讀進(jìn)String
fn read_exact(&mut self, buf: &mut [u8]) -> Result<[()]> { ... } // 讀滿buf
fn by_ref(&mut self) -> &mut Self
where
Self: Sized,
{ ... }
fn bytes(self) -> Bytes<Self> //迭代器
where
Self: Sized,
{ ... }
fn chars(self) -> Chars<Self> //迭代器,迭代UTF-8
where
Self: Sized,
{ ... }
fn chain<R: Read)>(self, next: R) -> Chain<Self, R>
where
Self: Sized,
{ ... }
fn take(self, limit: u64) -> Take<Self>
where
Self: Sized,
{ ... }
}
之前用到的read_to_string方法主要源自于File應(yīng)用了Read這個(gè)trait
Read的這些方法可以做一些騷操作庭惜,當(dāng)然我絕對(duì)是不會(huì)用的罩驻,無(wú)敵String,然后關(guān)我屁事护赊。
復(fù)制于:
https://doc.rust-lang.org/std/io/trait.Read.html