![1.png](https://static.studygolang.com/190214/f21a92b2c3fe7e9321645b6c43dfd17f.png)
![2.png](https://static.studygolang.com/190214/673d4d106aa00437a272df3eb56ea38b.png)
![3.png](https://static.studygolang.com/190214/e4a3db059b9d845083aaf18096ae1e26.png)
![4.png](https://static.studygolang.com/190214/43f7eceea171e59918ee20ba84e21dc5.png)
![5.png](https://static.studygolang.com/190214/2eb3bd7d79d60aeb7ccfcd29f0330921.png)
写入28个字节,最后读的时候变成了30个字节
```golang
package main
import("fmt"
"math/rand"
"time"
"os"
"strconv"
)
func prorand()(slice []int){
for i:=0;i<10;i++{
r:= rand.New(rand.NewSource(time.Now().UnixNano()))
time.Sleep(time.Nanosecond)
slice = append(slice,r.Intn(100))
}
//print
for _,v := range slice{
fmt.Printf("%d ",v);
}
return ;
}
func writeFile(slice []int) bool{
filepth := "./a.txt"
//Create creates the named file with mode 0666 (before umask), truncating it if it already exists
file,_ := os.Create(filepth)
//file,_ := os.OpenFile(filepth,os.O_CREATE|os.O_WRONLY|os.O_TRUNC,0666)
defer file.Close()
var str string
for i:=0;i<len(slice);i++{
if i== len(slice)-1{
str += strconv.Itoa(slice[i])
}else{
str += strconv.Itoa(slice[i]) + "-"
}
//fmt.Printf("\r\n%s",str)
}
fmt.Println("ss",len(str))
file.WriteString(str)
//fmt.Println("\r\n",n,"#")
//fmt.Println("\r\n",n,"#")
//fmt.Printf("\r\n%d",n)
return true
}
func main(){
writeFile(prorand())
return ;
}
```
#4
更多评论
1. 创建rand实例只需要一次就行了,没必要在循环里一直创建
2. 可能你原来的文件里有数据 os.O_WRONLY | os.O_CREATE | os.O_TRUNC
#1