In C, I can use rewind back to the start, but I didn't found a similar way in Rust.
I want to open an existed file, and let the file pointer go back to the start point, write new words to it and cover the old one.
But now I can only write something after the last line of the original file and don't know how to change the file pointer.
I known that rust has a crate libc::rewind, but how to use it, or any other ways?
Use seek.
use std::io::{self, Seek, SeekFrom};
use std::fs::File;
fn main() -> io::Result<()> {
let mut file = File::open("foo.bar")?;
file.seek(SeekFrom::Start(0))?;
Ok(())
}
From version 1.55.0 onwards you can use rewind(). It is a syntactic wrapper around SeekFrom::Start(0):
use std::io::{self, Seek};
use std::fs::File;
fn main() -> io::Result<()> {
let mut file = File::open("foo.bar")?;
file.rewind()?;
Ok(())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With