从阅读器中读取字节

时间:2014-10-15 09:32:26

标签: rust

我正在写一些以字节为单位处理stdin的东西,但似乎找不到一种简单的方法(虽然我怀疑有一个)。

fn run() -> int {
    // Doesn't compile: types differ
    let mut buffer = [0, ..100];
    loop {
        let block = match stdio::stdin().read(buffer) {
            Ok(bytes_read) => buffer.slice_to(bytes_read),
            // This captures the Err from the end of the file,
            // but also actual errors while reading from stdin.
            Err(message) => return 0
        };
        process(block).unwrap();
    }
}

fn process(block: &[u8]) -> Result<(), IoError> {
  // do things
}

我的问题:

2 个答案:

答案 0 :(得分:3)

Rust API文档声明:

  

请注意,文件结尾被视为错误,可以进行检查   在错误的类型字段中。

IoError结构如下所示:

pub struct IoError {
    pub kind: IoErrorKind,
    pub desc: &'static str,
    pub detail: Option<String>,
}

所有类型的列表都在http://doc.rust-lang.org/std/io/enum.IoErrorKind.html

你可以这样匹配:

match stdio::stdin().read(buffer) {
    Ok(_) => println!("ok"),
    Err(io::IoError{kind:io::EndOfFile, ..}) => println!("end of file"),
    _ => println!("error")
}

答案 1 :(得分:2)

之前接受的答案已过时( Rust v1.0 )。 EOF no longer considered出错。你可以这样做:

use std::io::{self, Read};

fn main() {
    let mut buffer = [0; 100];
    while let Ok(bytes_read) = io::stdin().read(&mut buffer) {
        if bytes_read == 0 { break; }
        process(&buffer[..bytes_read]).unwrap();
    }
}

fn process(block: &[u8]) -> Result<(), io::Error> {
    Ok(()) // do things
}

请注意,这可能不会导致预期的行为:read不必填充缓冲区,但可以返回任意数量的字节读取。在stdin的情况下,每次检测到换行符时都会返回read实现(按下在终端中输入)。

相关问题