File create Example (Write Bytes to File)
This page was last reviewed on Feb 24, 2023.
Dot Net Perls
File create. 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.
File Read Bytes
Example. 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.
Vec push
Info To read the existing data, we must pass a mutable reference to our vector to read_to_end.
Note The for-loop is where we modify the existing data, and push new byte elements (u8) as we go along.
Detail We open a file for writing by calling 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: 99
Modify existing file. 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.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 24, 2023 (edit).
© 2007-2024 Sam Allen.