2 回答
TA贡献1765条经验 获得超5个赞
您可以使用
file.WriteString(fmt.Sprintln(p))
一个完整的例子:
/*path of the file test.txt : you have to change it*/
var path = "/Users/Pippo/workspace/Go/src/......./test.txt"
func main() {
p := []int{1, 2, 3, 4, 5, 8, 99}
fmt.Println(p)
createFile()
writeFile(p)
}
/*create file*/
func createFile() {
// detect if file exists
var _, err = os.Stat(path)
// create file if not exists
if os.IsNotExist(err) {
var file, err = os.Create(path)
if isError(err) {
return
}
defer file.Close()
}
fmt.Println("==> done creating file", path)
}
/* print errors*/
func isError(err error) bool {
if err != nil {
fmt.Println(err.Error())
}
return (err != nil)
}
/*writeFile write the data into file*/
func writeFile(p []int) {
// open file using READ & WRITE permission
var file, err = os.OpenFile(path, os.O_RDWR, 0644)
if isError(err) {
return
}
defer file.Close()
// write into file
_, err = file.WriteString(fmt.Sprintln(p))
if isError(err) {
return
}
// save changes
err = file.Sync()
if isError(err) {
return
}
fmt.Println("==> done writing to file")
}
- 2 回答
- 0 关注
- 195 浏览
添加回答
举报