Overwriting file without opening it again using truncate

My project uses a config file. The config_file is stored in one variable, and the deserialised config is stored in another variable. Almost all functions use the deserialised config. However there is one function that needs the config_file and that is the write function. The write function is supposed to overwrite existing data and write a new serialised config. A solution I thought of is to .truncate() the file whenever writing to it (because I want to overwrite the file). But the truncate function only sets the length to 0, the cursor is left wherever it was previously. This is a problem because when I now write to the file, there are a bunch of NULL characters at the lead of the file. This causes serde to freak out and obviously, no one wants to open a file and see a bunch of NULLs leading it. I couldn't find any set_cursor method either. Is my only option to reopen the file with truncate(true)?

You can call seek with the argument SeekFrom::Start(0).

Thanks it worked! Looks like there will be a rewind method in the future to make it even more concise.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.