How to create a file in Rust?
An instance of a File can be read and/or written depending on what options it was opened with. Files also implement Seek to alter the logical cursor that the file contains internally.Example of how to create a file in Rust
Below example will create a file (filename: helloWorld.txt) using methodcreate()
and the content (will be Hello, world!) using method write_all()
, write all method take parameter as bytes so we need to add b
before the content or convert it to bytes as variable and use it. use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::create("helloWorld.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
}