Golang: Clear File Contents
In Golang, one way to clear the contents of a file is to use the ioutil.WriteFile function to overwrite the file content. Here is an example code:
package main
import (
"io/ioutil"
)
func main() {
filePath := "example.txt"
// 清空文件内容
err := ioutil.WriteFile(filePath, []byte(""), 0644)
if err != nil {
panic(err)
}
println("文件内容已清空")
}
In the code above, the file path example.txt to be cleared of its content is specified first. Then, the ioutil.WriteFile function is used to write an empty byte slice to the file, which will overwrite the existing content and clear the file. If there is an error, an exception will be thrown.