代码段正在尝试计算以下sample.txt
sample.txt
one two three four five six
seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen
%
情况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
情况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
我似乎无法弄清楚这两种情况为何输出不同的结果。任何表示感谢的帮助
答案 0 :(得分:6)
来自BufRead.lines
的文档:
此函数返回的迭代器将产生
io::Result<String>
的实例。返回的每个字符串将 不 具有一个换行符。
您的计数减少了3,因为数据中有3行,第二个示例中不计算换行符。