Working with text files
In this recipe, we will learn how to read, write, create, truncate, and append text files. Armed with this knowledge, you will be able to apply all other recipes to files instead of in-memory strings.
How to do it...
- Create a Rust project to work on during this chapter with
cargo new chapter-three
. - Navigate into the newly created
chapter-three
folder. For the rest of this chapter, we will assume that your command line is currently in this directory. - Inside the
src
folder, create a new folder calledbin
. - Delete the generated
lib.rs
file, as we are not creating a library. - In the
src/bin
folder, create a file calledtext_files.rs
. - Add the following code and run it with
cargo run --bin text_files
:
1 use std::fs::{File, OpenOptions}; 2 use std::io::{self, BufReader, BufWriter, Lines, Write}; 3 use std::io::prelude::*; 4 5 fn main() { 6 // Create a file and fill it with data 7 let path = "./foo.txt"; 8 println!("Writing some data to '{}'", path); 9 ...