Help with writing byte to file


#1

So I’m learning Rust and I’d like some help to finish off a trivial app I am creating for fun.

I’ve just completed reading THE BOOK on functions and enums but nothing hard concrete of file I/O.

I’m creating an app that will split a PDF (or any file, binary and text) into smaller chunks of files. I got everything but I’m stuck writing bytes to the chunked file(S)…any help would be appreciated…

https://play.rust-lang.org/?gist=a640abfd4f6f14ad8f3cb192e147ff80&version=stable


#2

Here’s a start:
https://play.rust-lang.org/?gist=46ea479e91a460d04fb2ae7d6fcaeeb5&version=stable

let file = File::open("bdd.pdf").expect("opening file failed");
let mut reader = BufReader::new(file);
let mut buf = vec![];
for chunk in 0.. {
    println!("File#:{}", chunk);

    buf.truncate(0);
    match reader.by_ref().take(FILE_SIZE_CHUNK).read_to_end(&mut buf) {
        Ok(0) => break, // EOF
        Ok(part_size) => println!("PART SIZE={}", part_size),
        Err(e) => panic!("{}", e),
    }

    let file = File::create(&format!("x_{}.txt", chunk)).unwrap_or_else(|e| panic!("{}", e));

    BufWriter::new(file).write_all(&mut buf);
}

Some things I used:

  • by_ref(), take(), and read_to_end() are all methods on the Read trait. The docs for take and read_to_end should be pretty clear. The reason I use by_ref() is because without it, take will consume the BufReader (which takes self). (try removing .by_ref() and you will see)
  • File::create() is a convenient alternative to how you were using OpenOptions
  • expect and unwrap_or_else are common ways to deal with Err in code that intends to panic

#3

Sweet! Much appreciated.