How it works...

Our main function is split into three parts:

  1. Creating a file.
  2. Overwriting a file, which in this context is called truncating.
  3. Appending to a file.

In the first two parts, we load the entire content of the file into a single String and display it [11 and 18]. In the last one, we iterate over the individual lines in the file and print them [28].

File::open() opens a file in read-only mode and returns you a handle to it [39]. Because this handle implements the Read trait, we could now just directly read it into a string with read_to_string. However, in our examples, we wrap it first in a BufReader[42]. This is because a dedicated reader can greatly improve the performance of their resource access by collecting read instructions, which is called buffering, and executing them in big batches. For the first reading example, read_file[37], this doesn't make any difference whatsoever, as we read it all in one go anyway. We still use it because it is a good practice, as it allows us to flexibly change the exact reading mechanisms of our function later on without worrying about performance. If you want to see a function where a BufReader actually does something, look a little further down, to read_file_iterator[48]. It appears to read the file line by line. This would be a very inefficient operation when dealing with a large file, which is why a BufReader actually reads a large chunk of the file in one go and then returns that segment line by line. The result is optimized file reading without us even noticing or caring what is going on in the background, which is pretty convenient.

File::create() creates a new file if it doesn't exist, otherwise it truncates the file. In any case, it returns the same kind of File handle like File::open() did before. Another similarity is the BufWriter we wrap around it. Just like with the BufReader, we would be able to access our underlying file without it, but use it to optimize future accesses as well.

There are more options than just opening a file in read-only or truncation mode. We can use them by creating our file handle with  OpenOptions[69], which use the builder pattern we explored in the Using the builder pattern section in Chapter 1Learning the Basics. In our example, we are interested in the append mode, which lets us add content to a file instead of overwriting it on every access.

For a full list of all available options, see the OpenOption documentation:
https://doc.rust-lang.org/std/fs/struct.OpenOptions.html.

We can read and write on the same file handle. For this, when creating the ReadBuf and WriteBuf, we pass a reference to the file instead of moving it, as the buffers would otherwise consume the handle, making sharing impossible:

let mut buf_reader = BufReader::new(&file);
let mut buf_writer = BufWriter::new(&file);

When doing this, be careful when appending and reading the same handle. The internal pointer that stored the current reading position might get shifted when appending. If you want to first read, then append, and then continue reading, you should save the current position before writing and then restore it afterward.

We can access our current position in the file by calling seek(SeekFrom::Current(0))[89]. seek moves our pointer by a certain amount of bytes and returns its new position. SeekFrom::Current(0) means that the distance we want to move is exactly zero bytes away from where we are right now. Because of this, as we don't move at all, seek will return our current position.

Then, we append our data using flush[92]. We have to call this method, as a BufWriter would normally wait for the actual writing until it is dropped, that is, it is no longer in scope. As we want to read before that happens, we use flush to force a write.

Finally, we get ready to read again by restoring our position from before, seeking it again:

buf_reader.seek(SeekFrom::Start(pos))?;

I invite you to run the code, look at the results, and then compare them with the output after commenting this line out.

..................Content has been hidden....................

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