如何使用固定大小的数组部分下载文件?

时间:2018-09-12 19:43:53

标签: rust

我想从URL下载文件。下面的代码可以正常工作,但是当我在Vec内将[u8; 4 * 1024]替换为read_to_end,将read替换为loop时,我会无限读取相同的信息。我应该如何更改代码以使用固定大小的数组分批下载文件?

use std::env;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Read, Result, Write};

//[dependencies]
//reqwest = "0.8.0"
extern crate reqwest;

fn main() -> Result<()> {
    // All URL's are stored in file passed as a command line argument
    let args: Vec<String> = env::args().collect();
    let fin = File::open(&args[1])?;

    let buf: &mut Vec<u8> = &mut Vec::new();
    let mut readed: usize;
    for line in BufReader::new(fin).lines() {
        let unwrapped = &line.unwrap();
        let mut options = OpenOptions::new();

        // Create an output file with a name equal to the last domain
        let fout = options
            .write(true)
            .create(true)
            .open(&unwrapped[unwrapped.rfind('/').unwrap() + 1..])?;
        let mut writer = BufWriter::new(&fout);

        readed = reqwest::get(unwrapped).unwrap().read_to_end(buf).unwrap();
        println!("{}", readed); // Just to know how many read
        writer.write(buf)?;

        // Close the file and clear "buf" to ensure that
        // the subsequent reading is correct
        writer.flush()?;
        buf.clear();
    }
    Ok(())
}

0 个答案:

没有答案