当未实现 Seek 时,如何从 std::io::Read 特征推进数据? [英] How to advance through data from the std::io::Read trait when Seek isn't implemented?

查看:13
本文介绍了当未实现 Seek 时,如何从 std::io::Read 特征推进数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当输出的内容不重要时,从实现 std::io::Read 特征的类型读取的最佳方法是什么?

What's the best way to read from a type implementing the std::io::Read trait when the contents of the output isn't important?

我看到的可能选项是:

  • 循环读取单个字节.
  • 分配一个可能很大的向量并读入它.
  • 介于两者之间... 在循环中读入固定大小的缓冲区.
  • Read single bytes in a loop.
  • Allocate a potentially huge vector and read into that.
  • Something in-between... read into a fixed sized buffer in a loop.

前两个选项似乎不太理想,第三个还可以但不方便.

The first 2 options don't seem ideal, the third is OK but inconvenient.

Rust 是否提供了一种方便的方法来实现这一点?

Does Rust provide a convenient way to achieve this?

推荐答案

您可以使用 io::copy()Read::take()io::sink() 丢弃特定数量的字节:

You can use io::copy(), Read::take() and io::sink() to discard a specific number of bytes:

let mut file = File::open("foo.txt").unwrap();

// Discard 27 bytes
io::copy(&mut file.by_ref().take(27), &mut io::sink());

// Read the rest
let mut interesting_contents = Vec::new();
file.read_to_end(&mut interesting_contents).unwrap();

(游乐场)

这里,我们也必须使用by_ref() 以便之后仍然可以使用该文件.

Here, we also have to use by_ref() in order to be able to still use the file afterwards.

这篇关于当未实现 Seek 时,如何从 std::io::Read 特征推进数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆