Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewind the file pointer in rust

Tags:

rust

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?

like image 843
moon548834 Avatar asked Nov 16 '25 22:11

moon548834


2 Answers

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(())
}
like image 122
Francis Gagné Avatar answered Nov 18 '25 19:11

Francis Gagné


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(())
}

like image 28
jmcnamara Avatar answered Nov 18 '25 21:11

jmcnamara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!