Snippet is trying to count the number of bytes read in the following sample.txt
sample.txt
one two three four five six
seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen
%
case 1:
let file = File::open(fname)?;
let mut reader = BufReader::new(&file);
let mut buffer: Vec<u8> = vec![];
let num_bytes = reader.read_until(b'%', &mut buffer);
//println!("{}", String::from_utf8(buffer).unwrap());
println!("read_bytes: {}", num_bytes.unwrap());
read_bytes: 101
case 2:
let file = File::open(fname)?;
let mut reader = BufReader::new(&file);
let mut num_bytes: u32 = 0;
for readline in reader.lines() {
if let Ok(line) = readline {
//println!("{}", line);
let bytes = line.as_bytes();
num_bytes += bytes.len() as u32;
if bytes == b"%" {
break;
}
}
}
println!("read_bytes: {}", num_bytes)
read_bytes: 98
I can't seem to figure out why the two cases are outputting different results. Any help with appreciated thanks
From the docs for BufRead.lines:
The iterator returned from this function will yield instances of
io::Result<String>. Each string returned will not have a newline byte.
Your count is off by 3 because you have 3 lines in the data and newline characters are not being counted in the second example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With