File writer functions has different behavior when the file is read

I’m not sure if this is intended behavior or if it’s a bug. The function std.fs.File.write() does has different behavior when that file is read previously.

when I run this code multiple times.

var file = try std.fs.cwd().openFile("text.txt", .{ .mode = .read_write });
defer file.close();

_ = try file.write("Some data\n");

that string will be written to the file only once.

However, when I run this code multiple times

var file = try std.fs.cwd().openFile("text.txt", .{ .mode = .read_write });
defer file.close();

var buffer: [64]u8 = undefined;
_ = try file.readAll(&buffer);

_ = try file.write("Some data\n");

that string appears on that file multiple times.

The function that reads the file moves the writer to the end of the file. When the data is written without reading, it overwrites that data over the file content without clearing it.

the zig version I’m using is 0.13.0.

If this is intentional, how to clear the old file content before writing the new one?

The file internally has a read/write position. After you read all the data, this position will be at the end of the file, so it will insert data there.
Doing file.seekTo(0) before writing or maybe file.setEndPos(0) might help (I haven’t tested this, so I’m not 100% sure here).

1 Like

You are right. But now it writes over the existing data of the file. How do I clear the file before writing?

You can call file.setEndPos(0), thus truncating the file.

2 Likes

Thank you. It works as I expected