Working with binary files
We are now going to combine what we learned in the last two chapters in order to parse and write binary files. This will prove essential when you plan on implementing custom, manual processing of file types such as PDFs, torrents, and ZIPs. It will also come in handy when designing custom file types for your own use cases.
How to do it...
If you haven't done it already in the last chapter, open the
Cargo.toml
file that was generated earlier for you.- Under
[dependencies]
, add the following line:
byteorder = "1.1.0"
- If you want, you can go to byteorder's crates.io page (https://crates.io/crates/byteorder) to check for the newest version and use that one instead.
In the
bin
folder, create a file calledbinary_files.rs
.Add the following code and run it with
cargo run --bin binary_files
:
1 extern crate byteorder; 2 use byteorder::{ByteOrder, ReadBytesExt, WriteBytesExt, BE, LE}; 3 use std::fs::File; 4 use std::io::{self, BufReader, BufWriter, Read}; 5 use...