简体   繁体   English

如何获取文件中当前的cursor position?

[英]How to get the current cursor position in file?

Given this code:鉴于此代码:

let any_offset: u64 = 42;
let mut file = File::open("/home/user/file").unwrap();
file.seek(SeekFrom::Start(any_offset));
// println!("{:?}", file.cursor_position()) 

How can I obtain the current cursor position?如何获取当前的cursor position?

You should call Seek:seek with a relative offset of 0. This has no side effect and returns the information you are looking for.您应该使用 0 的相对偏移调用Seek:seek 。这没有副作用并返回您要查找的信息。

Seek is implemented for a number of types, including: Seek实现了多种类型,包括:

  • impl Seek for File
  • impl<'_> Seek for &'_ File
  • impl<'_, S: Seek +?Sized> Seek for &'_ mut S
  • impl<R: Seek> Seek for BufReader<R>
  • impl<S: Seek +?Sized> Seek for Box<S>
  • impl<T> Seek for Cursor<T> where
  • impl<W: Write + Seek> Seek for BufWriter<W>

Using the Cursor class mentioned by Aaronepower might be more efficient though, since you could avoid having to make an extra system call.不过,使用Aaronepower 提到Cursor类可能更有效,因为您可以避免进行额外的系统调用。

According to the Seek trait API the new position is returned with the seek function.根据Seek trait API,新位置通过 seek 函数返回。 However you can also take the data of the File , and place it within a Vec , and then wrap the Vec in a Cursor which does contain a method which gets the current position.但是,您也可以获取File的数据,并将其放在Vec中,然后将Vec包装在Cursor中,该 Cursor 包含获取当前位置的方法。

Without Cursor无光标

let any_offset: u64 = 42;
let mut file = File::open("/home/user/file").unwrap();
let new_position = file.seek(SeekFrom::Start(any_offset)).unwrap();
println!("{:?}", new_position);

With Cursor带光标

use std::io::Cursor;

let any_offset: u64 = 42;
let mut file = File::open("/home/user/file").unwrap();
let contents = Vec::new();
file.read_to_end(&mut contents);
let mut cursor = Cursor::new(contents);
cursor.seek(SeekFrom::Start(any_offset));
println!("{:?}", cursor.position());

As of Rust 1.51.0 (2021) there is now the method stream_position() on the Seek trait.从 Rust 1.51.0 (2021) 开始, Seek特性上现在有方法stream_position()

use std::io::Seek;

let pos = file.stream_position().unwrap();

However, looking at the source code in the linked documentation this is purely a convenience wrapper that uses the same SeekFrom::Current(0) implementation behind the scenes.但是,查看链接文档中的源代码,这纯粹是一个方便的包装器,它在幕后使用相同的SeekFrom::Current(0)实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM