Rust:如何逐块读取文件 [英] Rust: How to read a file block by block

查看:491
本文介绍了Rust:如何逐块读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不生锈.我想按块/块(每个块应包含16个字节)读取一个文件块,并将其写入此文件(对于此测试方案)到另一个文件f2中.所以我首先在这里用此代码尝试了它:

i am totally new to rust. I want to read a file block by block/Chunks (every block should contain 16 Bytes) and write it - for this test scenario - into another file, f2. So i i tried it first with this code here:

let mut buf = [0;16];
let mut count = 0;

     for byte in f1.bytes() {

            if count  == 16 {
                do_smth(&mut f2, &mut buf);
                count = 0;
                let data = byte?;
                buf[count] = data;

            } else {
                let data = byte?;
                buf[count] = data;
                count +=1;
            }

    }

文件f1中的测试字节为:

The test bytes in the file f1 were:

0123456789abcdef-hello world, hello world!

文件f2中的结果为

0123456789abcdefhello world, hel

是否有一种高效的方法可以在每次迭代时增加文件光标. 我阅读了关于seek函数的信息,并对其进行了一些尝试,但并未找到解决方案.也许可以通过每次交互增加文件光标来解决此问题?

Is there a performant way to increment the file cursor each iteration. I read about the seek function and experimented a little with it but didn't come to a solution. Maybe this could be solved with an increment of the file cursor each interation?

推荐答案

为了提高性能,您可以考虑两件事:

There are two thing you could consider in order to improve performance:

  1. File包裹在BufReader中,以减少系统调用的次数,并从本质上对您的文件访问进行分块.
  2. 您可能想查看内存映射包,以使用内存映射文件.
  3. li>
  1. Wrapping File in a BufReader to reduce the number of system calls and essentially chunking your file access.
  2. You might want to check out the memmap crate, to use a memory mapped file.

这篇关于Rust:如何逐块读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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