Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create slice with filenames

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading