Truncate file in golang

When truncating a file, it appears to add extra null bytes to zero:

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 content, which I write at the beginning of the 0

bytes at the beginning.

How to trim and completely overwrite a file without leading zeros?

+3


source to share


1 answer


See documentation at Truncate

:

Truncation resizes the file. It doesn't change the I / O offset . If there is an error, it will be of type * PathError.



So you also need to look for the beginning of the file before writing:

configFile.Truncate(0)
configFile.Seek(0,0)

      

+5


source







All Articles