Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current cursor position in file?

Tags:

file

rust

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?

like image 484
AndreyT Avatar asked Jan 19 '16 14:01

AndreyT


People also ask

How do we get current position of file pointer?

position = ftell( fileID ) returns the current location of the position pointer in the specified file. If the query is successful, then position is a zero-based integer that indicates the number of bytes from the beginning of the file.

Which function returns the current pointer position within a file?

The ftell() function returns the current position of the read/write pointer in an open file.

Which function is used to move the cursor position in file?

fseek() is used to move file pointer associated with a given file to a specific position. position defines the point with respect to which the file pointer needs to be moved.

When file is open that time current location of file pointer is?

File handle is also called as file pointer or cursor. For example, when you open a file in write mode, the file pointer is placed at the 0th position, i.e., at the start of the file.


1 Answers

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.

like image 67
David Grayson Avatar answered Nov 15 '22 06:11

David Grayson