In order to write to a file - to create a new file and write some text in it - we can do the following.
We use the File struct that represents and open file. The create method will create a new file or truncate the content of the file if it already exists. Meaning that if we don't write anything to the file we'll now have an empty file. Regardless if it existed before and if it had content before.
As this might fail the function returns a Result struct that we need to deal with.
In this example we opted the use of the trailing question mark ?
(See the Evolution of error handling in Rust for an explanation.)
For this to work we also had to set up the main function to return a Result
as explained in Result returned by main function in Rust.
We can use the returned value in a writeln! to write the content to the file.
There is no need to explicitly close the file as files are automatically closed in the drop destructor when they go out of scope.
examples/files/write-to-file/src/main.rs
use std::fs::File;
use std::io::Write;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let filename = "data.txt";
let mut file = File::create(filename)?;
writeln!(&mut file, "Hello World!")?;
Ok(())
}
One thing that still disturbs me in this example is the fact that we need to have use std::io::Write;
in the code, but we then don't use the Write
name.
That's because Write is a trait that adds functionality to the File
which is used in the writeln!
macro.