Search code examples
rustiofile-writing

Extra lines getting written when writing a file with rust


I have a struct Point {x: f64, y: f64}. I also have a vector of line segments Vec<(Point, Point)>.

I am writing a collection of lines to a file like this.

let lines = make_lines();
let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .open("./points1")
        .unwrap();
for (p1, p2) in lines {
    writeln!(file, "{} {} {} {}", p1.x, p1.y, p2.x, p2.y).unwrap();
}

The vector always has 1000 lines. But the file sometimes gets written with 10001, 10002 lines. Also, maybe related is that those extra lines sometimes have 3 numbers.

I want to create the file if it doesn't exist and overwrite it if it does.


Solution

    1. you might be missing a .truncate(true), I'm not sure what the cursor position otherwise is when opening an existing file

    2. the file should definitely have 10001 lines, as writeln will always add a trailing newline you will have a final empty line, which is expected (and normal for unix files)

    Without a reproduction case there's not much else that can be said, you could try to flush / sync the writes explicitely to ensure they're on disk but apparently you're not missing data.