How to do it...

  1. Create a Rust project to work on during this chapter with cargo new chapter-three.
  2. 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.
  3. Inside the src folder, create a new folder called bin.
  4. Delete the generated lib.rs file, as we are not creating a library.
  5. In the src/bin folder, create a file called text_files.rs.
  6. 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 write_file(path, "Hello World! ").expect("Failed to write to
file");
10 // Read entire file as a string
11 let content = read_file(path).expect("Failed to read file");
12 println!("The file '{}' contains:", path);
13 println!("{}", content);
14
15 // Overwrite the file
16 println!("Writing new data to '{}'", path);
17 write_file(path, "New content ").expect("Failed to write to
file");
18 let content = read_file(path).expect("Failed to read file");
19 println!("The file '{}' now contains:", path);
20 println!("{}", content);
21
22 // Append data to the file
23 println!("Appending data to '{}'", path);
24 append_file(path, "Some more content ").expect("Failed to
append to file");
25 println!("The file '{}' now contains:", path);
26 // Read file line by line as an iterator
27 let lines = read_file_iterator(path).expect("Failed to read
file");
28 for line in lines {
29 println!("{}", line.expect("Failed to read line"));
30 }
31
32 append_and_read(path, "Last line in the file,
goodbye").expect("Failed to read and write file");
}
  1. These are the functions called by the main() function:
37   fn read_file(path: &str) -> io::Result<String> {
38 // open() opens the file in read-only mode
39 let file = File::open(path)?;
40 // Wrap the file in a BufReader
41 // to read in an efficient way
42 let mut buf_reader = BufReader::new(file);
43 let mut content = String::new();
44 buf_reader.read_to_string(&mut content)?;
45 Ok(content)
46 }
47
48 fn read_file_iterator(path: &str) ->
io::Result<Lines<BufReader<File>>> {
49 let file = File::open(path)?;
50 let buf_reader = BufReader::new(file);
51 // lines() returns an iterator over lines
52 Ok(buf_reader.lines())
53 }
54
55
56 fn write_file(path: &str, content: &str) -> io::Result<()> {
57 // create() opens a file with the standard options
58 // to create, write and truncate a file
59 let file = File::create(path)?;
60 // Wrap the file in a BufReader
61 // to read in an efficient way
62 let mut buf_writer = BufWriter::new(file);
63 buf_writer.write_all(content.as_bytes())?;
64 Ok(())
65 }
66
67 fn append_file(path: &str, content: &str) -> io::Result<()> {
68 // OpenOptions lets you set all options individually
69 let file = OpenOptions::new().append(true).open(path)?;
70 let mut buf_writer = BufWriter::new(file);
71 buf_writer.write_all(content.as_bytes())?;
72 Ok(())
73 }
  1. Reading and writing on the same handle:
76   fn append_and_read(path: &str, content: &str) -> io::Result<()
{
let file =
77 OpenOptions::new().read(true).append(true).open(path)?;
78 // Passing a reference of the file will not move it
79 // allowing you to create both a reader and a writer
80 let mut buf_reader = BufReader::new(&file);
81 let mut buf_writer = BufWriter::new(&file);
82
83 let mut file_content = String::new();
84 buf_reader.read_to_string(&mut file_content)?;
85 println!("File before appending: {}", file_content);
86
87 // Appending will shift your positional pointer
88 // so you have to save and restore it
89 let pos = buf_reader.seek(SeekFrom::Current(0))?;
90 buf_writer.write_all(content.as_bytes())?;
91 // Flushing forces the write to happen right now
92 buf_writer.flush()?;
93 buf_reader.seek(SeekFrom::Start(pos))?;
94
95 buf_reader.read_to_string(&mut file_content)?;
96 println!("File after appending: {}", file_content);
97
98 Ok(())
99 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.64.172