如何在 Rust 中倒带文件指针

moo*_*834 1 rust

在 C 中,我可以使用rewindback to start,但我没有在 Rust 中找到类似的方法。

我想打开一个已经存在的文件,让文件指针回到起点,往里面写新词,覆盖旧词。

但是现在我只能在原始文件的最后一行之后写一些东西,并且不知道如何更改文件指针。

我知道 rust 有一个板条箱libc::rewind,但如何使用它,或任何其他方式?

jmc*_*ara 6

从版本 1.55.0 开始,您可以使用rewind(). 它是一个语法包装器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(())
}

Run Code Online (Sandbox Code Playgroud)


Fra*_*gné 5

使用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(())
}
Run Code Online (Sandbox Code Playgroud)