如果文件较短,如何读取文件的前 N ​​个字节或更少?

Tim*_*mmm 5 rust

有没有一种简单的方法可以在 Rust 中读取文件的前 N ​​个字节?两个最相关的函数似乎是readread_exact,但read无论出于何种原因,返回的字节数都比可用的字节数少,所以我必须在一个烦人的循环中调用它,并且read_exact如果文件短于 N 个字节则放弃(而我更喜欢它只是读取整个文件)。

这不是这个问题的重复,可以通过以下方式解决read_exactHow to read a certain number of bytes from a stream?

Tim*_*mmm 4

我只是复制read_exact实现并稍微修改一下。它已经非常接近预期的工作了。

/// This is the same as read_exact, except if it reaches EOF it doesn't return
/// an error, and it returns the number of bytes read.
fn read_up_to(file: &mut impl std::io::Read, mut buf: &mut [u8]) -> Result<usize, std::io::Error> {
    let buf_len = buf.len();

    while !buf.is_empty() {
        match file.read(buf) {
            Ok(0) => break,
            Ok(n) => {
                let tmp = buf;
                buf = &mut tmp[n..];
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(buf_len - buf.len())
}
Run Code Online (Sandbox Code Playgroud)

(完全未经测试!)