rust读取文件

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

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 121,970评论 17 134
  • 教育在于对困难脱敏,做日常渗透,不知不觉不小心学会。 教育能力是化繁为极简,是容易,是简单,是朴素。 好老师是开门...
    咸叔说阅读 57评论 0 3
  • 第一章 她 莫无语 行走在江湖,倾城之色,年幼丧父母,跟在奕槐前辈身边,武功超群,行侠仗义,着红衣,手持“无意”剑...
    夏云悠滴小尾巴阅读 54评论 0 0