Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I truncate and completely rewrite a file without having leading zeros?

Tags:

go

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?

like image 952
Vit Kos Avatar asked Jun 07 '17 15:06

Vit Kos


People also ask

Can we truncate a file?

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.

How do I truncate a file in Linux?

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 .


1 Answers

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.

like image 89
Eric Pauley Avatar answered Sep 24 '22 01:09

Eric Pauley