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 theFile
type from thestd::fs
module.use std::io::prelude::*;
: This imports thewrite_all
method from thestd::io::prelude
module.let mut file = File::create("my_file.txt").expect("Failed to create file");
: This creates a new file calledmy_file.txt
and assigns it to thefile
variable.let string = "Hello, world!";
: This creates a string variable calledstring
and assigns it the value"Hello, world!"
.file.write_all(string.as_bytes()).expect("Failed to write to file");
: This writes the contents of thestring
variable to thefile
variable.
The output of the example code is a file called my_file.txt
containing the string Hello, world!
.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace all using regex in Rust?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- Hashshet example in Rust
- How to calculate the inverse of a matrix in Rust?
See more codes...