AndreyT
AndreyT

Reputation: 1499

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?

Upvotes: 11

Views: 13544

Answers (3)

JShorthouse
JShorthouse

Reputation: 1670

As of Rust 1.51.0 (2021) there is now the method stream_position() on the Seek trait.

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.

Upvotes: 7

David Grayson
David Grayson

Reputation: 87486

You should call Seek:seek with a relative offset of 0. This has no side effect and returns the information you are looking for.

Seek is implemented for a number of types, including:

  • 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.

Upvotes: 13

XAMPPRocky
XAMPPRocky

Reputation: 3619

According to the Seek trait API the new position is returned with the seek function. 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.

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

Upvotes: 3

Related Questions