我在打开文件时遇到麻烦。大多数示例将文件读入String
或将整个文件读入Vec
。我需要的是将文件读取为固定大小的块,并将这些块存储到块的数组(Vec
)中。
例如,我有一个大小为64 KB的名为my_file
的文件,我想以16KB的块大小读取它,因此我将得到一个大小为4的Vec
,其中每个元素都是另一个Vec
,大小为16Kb(0x4000字节)。
在阅读了文档并检查了其他Stack Overflow答案之后,我就能提供这样的东西:
let mut file = std::fs::File::open("my_file")?;
// ...calculate num_of_chunks 4 in this case
let list_of_chunks = Vec::new();
for chunk in 0..num_of_chunks {
let mut data: [u8; 0x4000] = [0; 0x4000];
file.read(&mut data[..])?;
list_of_chunks.push(data.to_vec());
}
尽管这似乎可以正常工作,但看起来有些令人费解。我读到:
Vec
中,然后移动到Vec
list_of_chunks
中。我不确定这是否是惯用的,甚至是可能的,但我宁愿有这样的内容:
Vec
个元素创建一个Vec
,其中每个元素都是另一个num_of_chunk
,大小为16KB。Vec
不进行复制,我们在读取文件之前确保已分配内存。
这种方法可行吗?还是有更好的常规/惯用/正确方法来做到这一点?
我想知道Vec
是否是解决此问题的正确类型。我的意思是,读取文件后,我不需要数组增长。
答案 0 :(得分:5)
Read::read_to_end
直接有效地读入Vec
。如果希望将其分块,请将其与Read::take
结合使用以限制read_to_end
将读取的字节数。
示例:
let mut file = std::fs::File::open("your_file")?;
let mut list_of_chunks = Vec::new();
let chunk_size = 0x4000;
loop {
let mut chunk = Vec::with_capacity(chunk_size);
let n = file.by_ref().take(chunk_size as u64).read_to_end(&mut chunk)?;
if n == 0 { break; }
list_of_chunks.push(chunk);
if n < chunk_size { break; }
}
最后一个if
不是必需的,但是它避免了额外的read
调用:如果read_to_end
读取的字节数少于请求的字节数,我们可以期待下一个{{ 1}}什么也不读,因为我们打到了文件末尾。
答案 1 :(得分:3)
我认为最惯用的方法是使用迭代器。以下代码(受M-ou-se's answer自由启发):
use std::io::{self, Read, Seek, SeekFrom};
struct Chunks<R> {
read: R,
size: usize,
hint: (usize, Option<usize>),
}
impl<R> Chunks<R> {
pub fn new(read: R, size: usize) -> Self {
Self {
read,
size,
hint: (0, None),
}
}
pub fn from_seek(mut read: R, size: usize) -> io::Result<Self>
where
R: Seek,
{
let old_pos = read.seek(SeekFrom::Current(0))?;
let len = read.seek(SeekFrom::End(0))?;
let rest = (len - old_pos) as usize; // len is always >= old_pos but they are u64
if rest != 0 {
read.seek(SeekFrom::Start(old_pos))?;
}
let min = rest / size + if rest % size != 0 { 1 } else { 0 };
Ok(Self {
read,
size,
hint: (min, None), // this could be wrong I'm unsure
})
}
// This could be useful if you want to try to recover from an error
pub fn into_inner(self) -> R {
self.read
}
}
impl<R> Iterator for Chunks<R>
where
R: Read,
{
type Item = io::Result<Vec<u8>>;
fn next(&mut self) -> Option<Self::Item> {
let mut chunk = Vec::with_capacity(self.size);
match self
.read
.by_ref()
.take(chunk.capacity() as u64)
.read_to_end(&mut chunk)
{
Ok(n) => {
if n != 0 {
Some(Ok(chunk))
} else {
None
}
}
Err(e) => Some(Err(e)),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.hint
}
}
trait ReadPlus: Read {
fn chunks(self, size: usize) -> Chunks<Self>
where
Self: Sized,
{
Chunks::new(self, size)
}
}
impl<T: ?Sized> ReadPlus for T where T: Read {}
fn main() -> io::Result<()> {
let file = std::fs::File::open("src/main.rs")?;
let iter = Chunks::from_seek(file, 0xFF)?; // replace with anything 0xFF was to test
println!("{:?}", iter.size_hint());
// This iterator could return Err forever be careful collect it into an Result
let chunks = iter.collect::<Result<Vec<_>, _>>()?;
println!("{:?}, {:?}", chunks.len(), chunks.capacity());
Ok(())
}