有一个每秒创建文件的程序。我想将文件名附加到切片中并打印出来。现在我的程序执行不正确,它附加名称但仅用于一个文件名。所以我希望得到[]string{"1","2","3"},而不是我得到[]string{"1","1","1"},[]string{"2","2","2"}, []string{"3","3","3"}。如何更正我的程序以获得预期结果?
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
"time"
)
func main() {
for {
time.Sleep(1 * time.Second)
createFile()
}
}
func createFile() {
rowFile := time.Now().Second()
fileName := strconv.Itoa(rowFile)
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
fmt.Println(err)
}
defer file.Close()
writer := csv.NewWriter(file)
writer.Comma = '|'
err = writer.Write([]string{""})
if err != nil {
fmt.Println(err)
}
countFiles(fileName)
}
func countFiles(fileName string) {
arrFiles := make([]string, 0, 3)
for i := 0; i < 3; i++ {
arrFiles = append(arrFiles, fileName)
}
fmt.Println(arrFiles)// here I expect ["1","2","3"] then ["4","5","6"] and so on. But now there is ["1","1","1"] then ["2","2","2"] and so on
}
FFIVE
相关分类