Home > database >  How to create slice with filenames
How to create slice with filenames

Time:09-13

There is a program which creates file per second. I want to append file names into slice and print them. Now my program executes incorrect, it appends names but only for one file name. So I expect to get []string{"1","2","3"}, instead I get []string{"1","1","1"}, []string{"2","2","2"}, []string{"3","3","3"}. How to correct my prog to get expected result?

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
}

CodePudding user response:

createFile() does not persist created file names in any way. You can do something like that:

 package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
    "time"
)

func main() {
    files := []string{}
    for {
        time.Sleep(1 * time.Second)
        files = append(files, createFile())
        fmt.Println(files)
    }
}

func createFile() string {
    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)
    }
    return fileName
}
  • Related