【发布时间】:2018-10-17 02:36:58
【问题描述】:
我正在尝试使用BufReader 加载一堆数据,然后使用read_until() 扫描数据。但是,我很难辨别read_until() 何时到达 EOF 并且我的代码再次回到数据的开头,从而创建了一个无限循环。当read_until() 到达 EOF 时,我需要停止阅读。我怎样才能在 Rust 中做到这一点?
这是我目前所拥有的:
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::str;
fn main() -> std::io::Result<()> {
let f1 = File::open("foo.txt")?;
let mut reader = BufReader::new(f1);
let mut byte_vec: Vec<u8> = Vec::new();
loop {
let my_bytes = reader.read_until(b'\n', &mut byte_vec);
let is_valid_utf8 = str::from_utf8(&byte_vec);
match is_valid_utf8 {
Ok(the_str) => println!("{} is a valid UTF-8 String", the_str),
Err(err) => println!("Error: {}", err),
}
}
Ok(())
}
foo.txt 只有几行示例文本。代码将永远循环回到文件的开头。
【问题讨论】:
-
1.为什么不使用 read_line ? 2. 阅读文档 3. 阅读警告
-
1.因为 read_line() 假设数据可以被解析为 utf8 并且我不能在我的代码中做出这个假设。 2. 特定领域的文档将很有用,而不仅仅是“阅读文档”——这与我的问题一样无用,您显然是在呼唤。理论上,每个 SO 问题都可以通过“阅读文档”来回答。来吧伙计。
-
@Stargateur 在看到
This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.之后,这意味着我必须扫描每个输入组的EOF?因此,必须有一个更有效的解决方案。顺便说一句,我在问之前确实读过。 -
EOF不是一个值。这是一种状态。在缓冲区中搜索它是没有意义的,它不作为值存在。
标签: io rust bufferedreader