如何获取文件中的当前光标位置? [英] How to get the current cursor position in file?

查看:136
本文介绍了如何获取文件中的当前光标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

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?

推荐答案

您应致电

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用于多种类型,包括:

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

使用 Cursor 可能会更有效,因为您可以避免进行额外的系统调用.

Using the Cursor class mentioned by Aaronepower might be more efficient though, since you could avoid having to make an extra system call.

这篇关于如何获取文件中的当前光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆