美文网首页
2020-05-07

2020-05-07

作者: 牛牛_076f | 来源:发表于2020-05-07 10:49 被阅读0次

    std::fs::File::open

    ```usestd::error::Error;usestd::fs::File;usestd::io::prelude::*;usestd::path::Path;fnmain(){// Create a path to the desired fileletpath=Path::new("hello.txt");letdisplay=path.display();// Open the path in read-only mode, returns `io::Result<File>`letmutfile=matchFile::open(&path){// The `description` method of `io::Error` returns a string that// describes the errorErr(why)=>panic!("couldn't open {}: {}",display,why.description()),Ok(file)=>file,};// Read the file contents into a string, returns `io::Result<usize>`letmuts=String::new();matchfile.read_to_string(&muts){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}

    ```

            

    select * from aa01;

            

    最后一句话看的出来rust可真他妈安全,都不用close了,当然因为这个特性写别的语言的时候可能就会忘掉这码事也不太好

    复制于:

    https://rustbyexample.com/std_misc/file/open.html

    usestd::env;usestd::fs::File;usestd::io::prelude::*;fnmain(){// --snip--println!("In file {}",filename);letmutf=File::open(filename).expect("file not found");letmutcontents=String::new();f.read_to_string(&mutcontents).expect("something went wrong reading the file");println!("With text:\n{}",contents);}

    跟上面丑丑的代码相比,官方书的代码稍微漂亮点,至少多用了个expect。。。

    复制于:

    https://doc.rust-lang.org/book/second-edition/ch12-02-reading-a-file.html

    trait std::io::Read

    pubtraitRead{fnread(&mutself,buf:&mut[u8])->Result<[usize]>;//返回读了多少个byteunsafefninitializer(&self)->Initializer{...}fnread_to_end(&mutself,buf:&mutVec<[u8]>)->Result<usize>{...}//全读进Vecfnread_to_string(&mutself,buf:&mutString)->Result<usize>{...}//全读进Stringfnread_exact(&mutself,buf:&mut[u8])->Result<[()]>{...}// 读满buffnby_ref(&mutself)->&mutSelfwhereSelf:Sized,{...}fnbytes(self)->Bytes<Self>//迭代器whereSelf:Sized,{...}fnchars(self)->Chars<Self>//迭代器,迭代UTF-8whereSelf:Sized,{...}fnchain<R:Read)>(self,next:R)->Chain<Self,R>whereSelf:Sized,{...}fntake(self,limit:u64)->Take<Self>whereSelf:Sized,{...}}

    之前用到的read_to_string方法主要源自于File应用了Read这个trait

    Read的这些方法可以做一些骚操作,当然我绝对是不会用的,无敌String,然后关我屁事。

    复制于:

    https://doc.rust-lang.org/std/io/trait.Read.html

    相关文章

      网友评论

          本文标题:2020-05-07

          本文链接:https://www.haomeiwen.com/subject/reuoghtx.html