如何使用`read_line()`检查EOF? [英] How to check for EOF with `read_line()`?
本文介绍了如何使用`read_line()`检查EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定下面的代码,我如何专门检查 EOF?或者更确切地说,我如何区分这里什么都没有"和它爆炸了"?
Given the code below, how can I specifically check for EOF? Or rather, how can I distinguish between "there's nothing here" and "it exploded"?
match io::stdin().read_line() {
Ok(l) => print!("{}", l),
Err(_) => do_something_else(),
}
推荐答案
来自 read_line
的文档:
From the documentation for read_line
:
如果成功,此函数将返回读取的总字节数.
If successful, this function will return the total number of bytes read.
如果此函数返回Ok(0)
,则流已达到EOF.
If this function returns Ok(0)
, the stream has reached EOF.
这意味着我们可以检查成功的零值:
This means we can check for a successful value of zero:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut empty: &[u8] = &[];
let mut buffer = String::new();
let bytes = empty.read_line(&mut buffer)?;
if bytes == 0 {
println!("EOF reached");
}
Ok(())
}
这篇关于如何使用`read_line()`检查EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文