Hello everyone, new Rust series episode is here. Last time we've tried reading text file, today we will try to create a new file and write some content to it.
Writing text to file
Again we will use API from std::fs and std::io. It will be pretty straightforward and if you are a good student of previous episodes it will be piece of cake for you to understand what is going on. First check simplified version with basic operations.
fn main() {
use std::io::prelude::*;
use std::fs::File;
let mut file = File::create("steemit_episode.txt").unwrap();
let text = b"Episode topic:\nWriting to file";
file.write_all(text);
}
Check file
Content of steemit_episode.txt will be
Episode topic:
Writing to file
Breaking down
Now we break down the basic code to explain more details.
std::io::prelude module alleviate import of many common io traits (like Read, Write, etc.). For us, it will provide write_all trait method.
File::create creates a new file. Note that like this if file exists it will be rewritten.
text contains text that will be written into a file by next statement. b”some string” takes &str and converts it to bytes array, specifically ref &[u8].
write_all is a method that writes all bytes into file called upon.
If we check file system we will see newly created "steemit_episode.txt" file in the project directory (in case we are using cargo).
With error handling
Let's use result composing to report possible errors with general way and specific OS details. Note that you have other options to achieve possibilities how to handle results here, check the error handling related episodes if needed.
fn main() {
use std::io::prelude::*;
use std::fs::File;
let text = b"Episode topic:\nWriting to file";
let result = File::create("steemit_episode.txt")
.map_err(|err| {
let mut ret = String::from("Cannot create file - ");
ret.push_str(&err.to_string());
return ret;
})
.and_then(|mut file| {
file.write_all(text)
.map_err(|err| {
let mut ret = String::from("Cannot write file - ");
ret.push_str(&err.to_string());
return ret;
})
});
match result {
Ok(_) => println!("File written successfully!"),
Err(err) => println!("Unable to proceed: {}", err)
};
println!("Application finished!")
}
Possible output
This is how result can look like. Of course various errors can occur and so you can get various error messages based on situation and OSs. This examples shows what we get if file already exists and we don't have permissions to overwrite it.
# output ok
File written
Application finished!
# output when error
Unable to proceed: Cannot create file - Permission denied (os error 13)
Application finished!
Perfect! Now our code is quite covered in terms of providing detailed information when something goes wrong.
Postfix
That's all for now, thank you for your appreciations, feel free to comment and point out possible mistakes (first 24 hours works the best but any time is fine). May Jesus bless your programming skills, use them wisely and see you next time.
Meanwhile you can also check the official documentation for more related information: