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 use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...