Suppose in Rust we have a file containing bytes (u8
elements) and want to modify the data. We then want to write the file in another location.
With u8
vectors, we can read in an existing file, and loop over the elements, building up a new vector. Then we can call File::create()
to write the new data to disk.
This example code uses the Vec::new()
function to create new vectors of u8
elements. These 2 vectors store the bytes read, and the bytes we will write.
read_to_end
.for
-loop is where we modify the existing data, and push new byte
elements (u8
) as we go along.File::create()
and then convert the u8
vector to a slice by calling as_slice
.use std::io; use std::io::Read; use std::io::BufReader; use std::fs::File; use std::io::prelude::*; fn main() -> io::Result<()> { // Read the file. let f = File::open("/Users/sam/file.txt")?; let mut reader = BufReader::new(f); let mut buffer = Vec::new(); reader.read_to_end(&mut buffer)?; // Loop over and modify the data. let mut buffer_modified = Vec::new(); for value in buffer { println!("BYTE: {}", value); if value == 'a' as u8 { let value_modified = 'z' as u8; buffer_modified.push(value_modified); println!("MODIFIED: {}", value_modified); } else { buffer_modified.push(value); } } // Add additional letter. buffer_modified.push('.' as u8); // Write the modified data. let mut f = File::create("/Users/sam/file-modified.txt")?; f.write_all(buffer_modified.as_slice())?; Ok(()) }BYTE: 97 MODIFIED: 122 BYTE: 98 BYTE: 99abczbc.
If we pass the same file name to the File::create
method that we used for File::open
, we can modify the same file. No additional file is needed.
By using u8
Vectors, we can read in a file and modify it in memory. Then we can write the modified data to a different file, or the same file, thus mutating the byte
file.