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

时间:2020-05-20 11:21:52

标签: file rust io seek

读取几行后,如何在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中移出,但没有告诉我当前位置。

1 个答案:

答案 0 :(得分:3)

关于第一个问题,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!");

正如评论中指出的那样,这仅在您尚未移动阅读器的情况下才有效,因此您还需要更改阅读循环以借用reader而不是移动它:

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