【问题标题】:How can I get the current position in a `BufReader` for a file? [duplicate]如何获取文件的“BufReader”中的当前位置? [复制]
【发布时间】:2020-05-20 11:21:52
【问题描述】:

阅读几行后,如何在 rust 打开的文件流中获取光标的当前位置?

例如: 在这里,我将光标从开始移动了 6 个字节。读到 50 个字符。在此之后,我想获取光标的当前位置,并从其位置再次寻找光标。

use std::fs::File;
use std::io::{BufReader, BufRead, SeekFrom};
use std::io::Seek;
use std::env;

fn main() {

    let fafile: String = "temp.fa".to_string();
    let mut file = File::open(fafile).expect("Nope!");
    let seekto: u64 = 6;
    file.seek(SeekFrom::Start(seekto)); //open a file and seek 6 bytes
    let reader = BufReader::new(file);

    let mut text: String = "".to_string();

    //Stop reading after 50 characters
    for line in reader.lines(){
        let line = line.unwrap();
        text.push_str(&line);
        if text.len() > 50{ 
            break;
        }
    }

   //How do I get the current position of the cursor? and
  // Can I seek again to a new position without reopening the file? 
  //I have tried below but it doesnt work.

   //file.seek(SeekFrom::Current(6)); 

}

我检查了seek,它提供将光标从startendcurrent 移动,但没有告诉我当前位置。

【问题讨论】:

  • 并非如此。正如comments 之一指出的那样,moved value 存在这个问题,这使得file 在第一次搜索后不再可访问。

标签: file rust io seek


【解决方案1】:

关于您的第一个问题,seek 在移动后返回新位置。因此,您可以通过从当前位置偏移 0 来获取当前位置:

let current_pos = reader.seek (SeekFrom::Current (0)).expect ("Could not get current position!");

(另见this question

关于第二个问题,将file 变量移入BufReader 后,您将无法再访问它,但您可以在阅读器本身上调用 seek:

reader.seek (SeekFrom::Current (6)).expect ("Seek failed!");

正如 cmets 中所指出的,这仅在您没有移动阅读器的情况下才有效,因此您还需要将阅读循环更改为借用 reader 而不是移动它:

for line in reader.by_ref().lines() {
    // ...
}

【讨论】:

  • 谢谢。不幸的是,reader 变量也存在同样的问题。我得到与value moved 相同的错误。我知道我想要的字符串在大文本文件中的确切位置。我需要从一个位置一个接一个地寻找而不重新打开文件以获得更快的随机访问。
  • 这不是同一个问题:现在您的读者正在被lines() 调用所消耗。您可以使用reader.by_ref().lines() 避免移动阅读器。
  • 太棒了。这行得通。
猜你喜欢
  • 2017-07-23
  • 1970-01-01
  • 2012-10-26
  • 2015-11-05
  • 2014-10-12
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2016-03-08
相关资源
最近更新 更多