【发布时间】: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,它提供将光标从start、end 和current 移动,但没有告诉我当前位置。
【问题讨论】:
-
并非如此。正如comments 之一指出的那样,
moved value存在这个问题,这使得file在第一次搜索后不再可访问。