美文网首页
rust读取文件

rust读取文件

作者: ppphp | 来源:发表于2018-03-12 01:44 被阅读0次

    内容都是谷歌前两个结果,我也不是谦虚,只是普通的复制粘贴

    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
    }
    

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

    复制于:
    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);
    }
    

    跟上面丑丑的代码相比,官方书的代码稍微漂亮点,至少多用了个expect。。。
    复制于:
    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]>; //返回读了多少个byte
    
        unsafe fn initializer(&self) -> Initializer { ... }
        fn read_to_end(&mut self, buf: &mut Vec<[u8]>) -> Result<usize> { ... } //全读进Vec
        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> { ... } //全读进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应用了Read这个trait
    Read的这些方法可以做一些骚操作,当然我绝对是不会用的,无敌String,然后关我屁事。
    复制于:
    https://doc.rust-lang.org/std/io/trait.Read.html

    相关文章

      网友评论

          本文标题:rust读取文件

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