gpt4 book ai didi

file - 从文件中读取一系列字节的最惯用方法

转载 作者:行者123 更新时间:2023-12-01 23:16:48 25 4
gpt4 key购买 nike

我有一个文件,比如 myfile。使用 Rust,我想打开 myfile,并将字节 N 到 M 读入 Vec,比如 myvec。最惯用的方法是什么?天真地,我想到了使用 bytes(),然后是 skiptakecollect,但这听起来效率很低.

最佳答案

最惯用的(据我所知)和相对有效的方式:

let start = 10;
let count = 10;

let mut f = File::open("/etc/passwd")?;
f.seek(SeekFrom::Start(start))?;
let mut buf = vec![0; count];
f.read_exact(&mut buf)?;

您在评论中指出您担心在读取内存之前将内存清零的开销。这确实有一个非零成本,但与从文件读取所需的 I/O 操作相比通常可以忽略不计,而且优点是您的代码保持 100% 健全。但仅出于教育目的,我试图提出一种避免归零的方法。

不幸的是,由于 documentation 中的这一段,我们无法安全地将未初始化的缓冲区传递给 read_exact (强调我的):

No guarantees are provided about the contents of buf when this function is called, implementations cannot rely on any property of the contents of buf being true. It is recommended that implementations only write data to buf instead of reading its contents.

所以 File::read_exact 从提供的缓冲区中读取 在技术上是合法的,这意味着我们不能在这里合法地传递未初始化的数据(使用 MaybeUninit).

关于file - 从文件中读取一系列字节的最惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68694399/

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