go - 如何在没有前导零的情况下截断并完全重写文件?

标签 go

截断文件时,它似乎在开头添加了额外的零字节:

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/

相关文章:

go - 如何检查 channel 是否仍在 streadway/amqp RabbitMQ 客户端中工作?

ssl - 带有 client.crt 和 client.key 的 https 请求

go - 定时器在 Golang 中是如何工作的

inheritance - Go 结构可以继承一组值吗?

go - 从 goroutine 中捕获返回值

go - 如果您从应用程序中按 ctrl-c,是否会运行延迟的 Restore()?

json - 如何使用键值结构数组解码 JSON,其中键没有 json 标记

Golang 博客 slice 和内部结构

go - 如何获取golang中两个目录内容之间的差异

mongodb - 无法创建/访问数据库