Rust編程知識拾遺:Rust 編程,讀取文件

視頻地址

頭條地址:https://www.ixigua.com/i6765442674582356483
B站地址:https://www.bilibili.com/video/av78062009?p=1
網易雲課堂地址:https://study.163.com/course/introduction.htm?courseId=1209596906#/courseDetail?tab=1

github地址

github地址

讀取文件

將文件讀取成二進制,使用read函數

use std::fs;

fn main() {
    let context = fs::read("tt").unwrap();
    println!("context: {:#?}", context);
}

將文件讀取成字符串

use std::fs;

fn main() {
    let context = fs::read_to_string("tt").unwrap();
    println!("context: {}", context);
}

讀取目錄

use std::io;
use std::fs;
use std::path::Path;

fn visit_dirs(dir: &Path) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path)?;
            } else {
                let c = fs::read_to_string(path).unwrap();
                println!("file = {}", c);
            }
        }
    }
    Ok(())
}

fn main() {
    //let context = fs::read("tt").unwrap();
    //println!("context: {:#?}", context);

    //let context = fs::read_to_string("tt").unwrap();
    //println!("context: {}", context);

    visit_dirs(Path::new("./test")).unwrap();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章