将一个int切片写入文件,想要写入内容和实际写入内容不一样,但是写入的字节数又没有问题,求大佬解决

duangkuang · · 930 次点击
haoyupei
大道至简,始终如一
```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 ; } ```
#5
更多评论
1. 创建rand实例只需要一次就行了,没必要在循环里一直创建 2. 可能你原来的文件里有数据 os.O_WRONLY | os.O_CREATE | os.O_TRUNC
#1
大佬牛逼,嗷嗷
#2