rust write to file
To write to a file in Rust, you can use the std::fs::File
struct and its associated methods. First, you'll need to open the file in write mode using the File::create
function, which returns a Result
type. Here's an example:
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::create("output.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
}
In this example, we import the necessary modules, create a File
object using File::create
, and then use the write_all
method to write the content to the file. The content is provided as a byte slice (b"Hello, world!"
).
The ?
operator is used to handle any potential errors that may occur during file creation or writing. If an error occurs, it will be propagated up the call stack.
Make sure to handle the std::io::Result
returned by the main
function appropriately in your application.