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

查看:78
本文介绍了当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() 阅读:: take() io :: sink() 放弃一个特定的c字节数:

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();

Playground

在这里,我们还必须使用 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天全站免登陆