Write to a file - create file in Rust

create writeln! File Write Error

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.

Related Pages

Keep you data safe using advisory lock on your files
Files - dealing with files in Rust
Append to a file

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo