When truncating a file it seems to be adding additional zero bytes to the start:
configFile, err := os.OpenFile("./version.json", os.O_RDWR, 0666)
defer configFile.Close()
check(err)
//some actions happen here
configFile.Truncate(0)
configFile.Write(js)
configFile.Sync()
As a result the file has the contents I write with a section of 0
bytes at the beginning.
How do I truncate and completely rewrite a file without having leading zeros?
You can truncate a file to a particular length, which might be zero. But truncating to zero isn't the same thing as deleting the file because the directory entry still exists, there's just no data in it. Or, you can truncate a file to some number of bytes, and write some more on the end, to change part of it.
To empty the file completely, use -s 0 in your command. Add a plus or minus sign in front of the number to increase or decrease the file by the given amount. If you don't have proper permissions on the file you're trying to truncate, you can usually just preface the command with sudo .
See the documentation on Truncate
:
Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type *PathError.
So you also need to seek to the beginning of the file before you write:
configFile.Truncate(0)
configFile.Seek(0,0)
As shorthand, use the flag os.O_TRUNC
when calling os.OpenFile
to truncate on open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With