Skip to content

Instantly share code, notes, and snippets.

@SoTosorrow
Created January 11, 2023 04:31
Show Gist options
  • Save SoTosorrow/2f3a6cee5789a975f49123213333681e to your computer and use it in GitHub Desktop.
Save SoTosorrow/2f3a6cee5789a975f49123213333681e to your computer and use it in GitHub Desktop.
Rust File'question about seek/buf
fn main() {
let mut file = File::options().read(true).write(true).open("json.txt").unwrap();
let mut file_reader = BufReader::new(file); // Rust文件读写是无缓冲的, 使用BufReader/BufWriter为文件读写增加缓冲
let mut result = String::new();
let mut result2 = String::new();
// Rust 文件操作会改变seek位置,且多个clone共享。当某个clone read_to_string后,此时file已经到EOF,其他clone再读也是空。必须重置seek
// let seek = file.seek(std::io::SeekFrom::Current(0)).unwrap();
// file.try_clone().unwrap().read_to_string(&mut result).unwrap();
// file.seek(std::io::SeekFrom::Start(seek)).unwrap();
// file.try_clone().unwrap().read_to_string(&mut result2).unwrap();
let seek = file_reader.seek(std::io::SeekFrom::Current(0)).unwrap();
file_reader.read_to_string(&mut result).unwrap();
file_reader.seek(std::io::SeekFrom::Start(seek)).unwrap();
file_reader.read_to_string(&mut result2).unwrap();
println!("{result:?}");
println!("{result2:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment