截断文件时,它似乎在开头添加了额外的零字节:
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()
结果文件中有我写的内容,开头有一段0
字节。
如何在没有前导零的情况下截断并完全重写文件?
最佳答案
参见 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.
所以你还需要在写之前寻找到文件的开头:
configFile.Truncate(0)
configFile.Seek(0,0)
作为简写,在调用 os.OpenFile
时使用标志 os.O_TRUNC
以在打开时截断。
关于go - 如何在没有前导零的情况下截断并完全重写文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416645/