簡體   English   中英

如何獲取文件中當前的cursor position?

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

鑒於此代碼:

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

如何獲取當前的cursor position?

您應該使用 0 的相對偏移調用Seek:seek 。這沒有副作用並返回您要查找的信息。

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>

不過,使用Aaronepower 提到Cursor類可能更有效,因為您可以避免進行額外的系統調用。

根據Seek trait API,新位置通過 seek 函數返回。 但是,您也可以獲取File的數據,並將其放在Vec中,然后將Vec包裝在Cursor中,該 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);

帶光標

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

從 Rust 1.51.0 (2021) 開始, Seek特性上現在有方法stream_position()

use std::io::Seek;

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

但是,查看鏈接文檔中的源代碼,這純粹是一個方便的包裝器,它在幕后使用相同的SeekFrom::Current(0)實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM