【问题标题】:How to read the first N bytes of a file or less if it is shorter? [duplicate]如果文件更短,如何读取文件的前 N ​​个字节或更短? [复制]
【发布时间】:2020-03-31 12:55:00
【问题描述】:

有没有一种简单的方法可以在 Rust 中读取文件的前 N ​​个字节?两个最相关的函数似乎是readread_exact,但read 可以返回比可用字节少的字节,所以我不得不在一个烦人的循环中调用它,如果read_exact 放弃了文件比 N 个字节短(而我希望它只读取整个文件)。

这不是这个问题的重复,可以用read_exact解决:How to read a specific number of bytes from a stream?

【问题讨论】:

标签: rust


【解决方案1】:

我只是复制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())
}

(完全未经测试!)

【讨论】:

  • 我想你链接了read_to_endread_exact 除非我是愚蠢的!
  • 是的,很抱歉!
  • 我确实认为这个答案更适合副本。
  • 所以你用 read 重新编码了read()
  • @Timmmm 所以我不得不在一个烦人的循环中调用它 这在你的问题中有所说明,但这个答案也有循环,你想重新考虑欺骗的答案吗?我以为您正在寻找更惯用或更简洁的解决方案?
猜你喜欢
  • 2020-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
相关资源
最近更新 更多