gpt4 book ai didi

rust - 如何从实现读取的类型中逐 block 读取?

转载 作者:行者123 更新时间:2023-12-03 11:29:53 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is the correct way to read a binary file in chunks of a fixed size and store all of those chunks into a Vec?

(2 个回答)


去年关闭。




我需要将数据读入精确大小的块中(最后一个块可能被部分填充)。理想情况下,此方法也适用于 Read 的所有类型。 .我最初的想法是这样的:

use std::io::{self, prelude::*};
use std::error;

const CHUNK_SIZE: usize = 2;

fn main() -> Result<(), Box<dyn error::Error>> {
let mut a = &[1u8, 2, 3, 4, 5][..]; // Some Read type
let mut buf = vec![0u8; CHUNK_SIZE];
loop {
match a.read_exact(&mut buf) {
Ok(_) => println!("{:?}", buf),
Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
Err(e) => return Err(e.into()),
}
}
buf.clear();
a.read_to_end(&mut buf)?;
println!("{:?}", buf);
Ok(())
}
这个玩具示例有效;然而,阅读 documentation for Read 我似乎无法推理它是否正确。文档说在失败后 read_exact缓冲区内容不能假设。请问 read_to_end失败后 read_exact总是检索那些剩余的字节?
这段代码是正确的还是有更好的方法来读取块?

最佳答案

如果您想确保分块读取有效,请使用 read ,不是 read_exact . read返回 Result<usize>读取的字节数,以及 0如果它到达EOF。这将确保它适用于部分数据。

关于rust - 如何从实现读取的类型中逐 block 读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63119014/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com