rustHow do you write a string to a file in Rust?
Writing a string to a file in Rust is a simple process. The following example code block shows how to do this:
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut file = File::create("my_file.txt").expect("Failed to create file");
let string = "Hello, world!";
file.write_all(string.as_bytes()).expect("Failed to write to file");
}
Code explanation
use std::fs::File;: This imports theFiletype from thestd::fsmodule.use std::io::prelude::*;: This imports thewrite_allmethod from thestd::io::preludemodule.let mut file = File::create("my_file.txt").expect("Failed to create file");: This creates a new file calledmy_file.txtand assigns it to thefilevariable.let string = "Hello, world!";: This creates a string variable calledstringand assigns it the value"Hello, world!".file.write_all(string.as_bytes()).expect("Failed to write to file");: This writes the contents of thestringvariable to thefilevariable.
The output of the example code is a file called my_file.txt containing the string Hello, world!.
Helpful links
More of Rust
- Regex example to match multiline string in Rust?
- How to use negation in Rust regex?
- How to use regex captures in Rust?
- How to use regex to match a double quote in Rust?
- How to extend a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to borrow from vector in Rust
- How to use non-capturing groups in Rust regex?
See more codes...