Rust, Software Development

Rust – How to read last few lines of a File

Sometimes we don’t want to load read all the content of a text file. For instance, we only want to see the last several lines. In Rust, we can use a crate called rev_lines to read and display the last few lines of a file without changing their order.

Rust Dependency In Cargo.toml To Read Lines.

The very first thing we need to do is add the dependency to the crate rev_lines to the Cargo.toml file.

Test Data To Read Last Lines

Consider the following contents of a file named logfile.log. It only has 15 lines with numbers from 1 to 15.

Suppose we want to display only the last 5 lines in the same order as they are in the file.  For example:

Rust Codes To Read Last Several Lines From A File

Using the Rust crate rev_lines to read the last several lines from a file is easy. First, we can use the extern and use keywords as shown below. Then, we create an instance of File to reference the logfile.log. Also, we need to create an instance of BufReader using the File instance. Next, we create a RevLines instance with an instance of BufReader. Note that when we create a RevLines instance, we load the whole content of the file to memory. However, the lines are in reversed order. Meaning the last line comes first.

Reading the whole file into memory may not be the best solution for most cases. But with Rust, our application should have a relatively smaller memory footprint when reading the whole file. So then, we can proceed with pick up only the first 5 lines using a loop.

Finally, we display the last 5 lines.

When we run the Rust codes, we get the following output showing the last 5 lines from the file.

Tested with Rust 1.52.1.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like