How shall I read out the last part of a file?

the content of the file looks like as below:

aaaaaa
aaaaaaaaaaaaaaaa
aaaaaaaaa

bbbbbbbbb
bbbb
bbbbbbbbbbbbbbbbb

cccccc
ccc
cccccc

There are 3 parts above and each one is seperated by a blank line, and sometimes there should be 5 or more parts. I jsut want to extract the last part whatever how many parts in all.
In the example I just want to get the 3 lines which contains 'c'.

One thing you can do is to read the full file into memory with std::fs::read_to_string(), split it into parts with split("\n\n"), then use the last() method all iterators get for free to extract the last part.

let text = std::fs::read_to_string("input.txt").expect("read failed");
let last_part = text.split("\n\n")
  .map(|part| part.trim())
  .filter(|part| !part.is_empty())
  .last()
  .expect("The file had no parts");

I threw in the map() and filter() so we'll automatically trim away trailing whitespace and drop any "empty" segments (e.g. if the file ended with an empty line).

2 Likes

Note that Michael's approach, thought quite simple, requires reading the entire file. You can instead seek to the end of the file and read out chunks, checking if they contain the pattern \n\n, until you find one or reach the start of the file. Note that reading out chunks like that can split a UTF-8 code point, you have to do all your work using Vec<u8> before converting to a String at the end.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.