pu369com

rust 读取文件

1、逐行读文本

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

fn main() {
    // File hosts must exist in current path before this produces output
    if let Ok(lines) = read_lines("./hosts") {
        // Consumes the iterator, returns an (Optional) String
        for line in lines {
            if let Ok(ip) = line {
                println!("{}", ip);
            }
        }
    }
}

// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

2 一次读入文本

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // Create a path to the desired myfile
    let path = Path::new("a.txt");
    let display = path.display();

    // Open the path in read-only mode, returns `io::Result<File>`
    let mut myfile = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why),
        Ok(myfile) => myfile,
    };

    // Read the myfile contents into a string, returns `io::Result<usize>`
    let mut s = String::new();
    match myfile.read_to_string(&mut s) {
        Err(why) => panic!("couldn't read {}: {}", display, why),
        Ok(_) => print!("{} contains:\n{}", display, s),
    }

    // `myfile` goes out of scope, and the "hello.txt" myfile gets closed
}

3  读取二进制文件 

use std::fs::File;
use std::env;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
    let mut param=env::args();
    if param.len() != 2{
        Err(std::io::Error::new(std::io::ErrorKind::Other,"usage:bintool inputfile"))
    }
    else{
        let _=param.next();
        let inputfile=param.next();
        let mut _inputfile = File::open(inputfile.unwrap())?;
        //let mut _outputfile= File::create(outputfile.unwrap())?;
        let mut buffer:[u8;16]=[0;16];
        while let std::io::Result::Ok(len) = _inputfile.read(&mut buffer){
            //println!("{}",len);
            if len == 0 {
                break;
            }
            else{
                for i in 0..len{
                    //_outputfile.write_fmt(format_args!("{:#02x} ",buffer[i]));
                    print!("{:02x} ",buffer[i]);
                }println!("\r\n");
            }
        }
        Ok(())
    }
}

 

 

 

参考:https://doc.rust-lang.org/rust-by-example/std_misc/file/open.html

https://www.it610.com/article/1282640012466208768.htm

posted on 2021-08-20 17:31  pu369com  阅读(806)  评论(0编辑  收藏  举报

导航