如何获取文件在`BufReader`中的当前位置?[重复]

问题描述 投票:0回答:1

在读取了几行文件后,我如何在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)); 

}

我已经检查了 谋求 它提供了移动光标从 start, endcurrent 但没有告诉我当前位置。

file rust io seek
1个回答
3
投票

关于你的第一个问题。seek 返回移动后的新位置。所以你可以通过寻找与当前位置偏移量为0的位置来获得当前位置。

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

(参见 这个问题)

关于第二个问题,你不能再访问 file 变量,一旦你把它移到 BufReader但你可以在阅读器本身调用seek。

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

正如评论中所指出的,这只有在你没有移动阅读器的情况下才会有效,所以你还需要改变你的阅读循环,以借用 reader 而不是移动它。

for line in reader.by_ref().lines() {
    // ...
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.