Wilhelm de Fheur Gorm
Wilhelm de Fheur Gorm

Reputation: 339

In Golang, how to add results from a loop into a dynamic array of unknown size?

The example I'm working with right now takes input from console asking for a file extension, say .txt . It searches the current directory for files and then does a Println which returns all the files with the .txt onto the screen.

For each result returned, how can I put each filename into an array (or a slice?) and then access each value later in the program to manipulate each file.

It doesn't need to be sequential.

This is the working code (modified from Adam Ng, I think)

     package main

  import (
      "fmt"
      "os"
      "path/filepath"
    "bufio"
    //"bytes"
    //"io/ioutil"

  )

  func main() {


    lineScan := bufio.NewScanner(os.Stdin)
    var inputText string

    fmt.Print("Enter file extension to search for: .extension \n")     
    lineScan.Scan()
    inputText = lineScan.Text()

      dirname := "." + string(filepath.Separator)

      d, err := os.Open(dirname)
      if err != nil {
          fmt.Println(err)
          os.Exit(1)
      }
      defer d.Close()

      files, err := d.Readdir(-1)
      if err != nil {
          fmt.Println(err)
          os.Exit(1)
      }

      for _, file := range files {
          if file.Mode().IsRegular() {

              if filepath.Ext(file.Name()) == inputText {

                fmt.Println(file.Name())
              }
          }
      }
  }

Upvotes: 0

Views: 4785

Answers (1)

daplho
daplho

Reputation: 1135

I tweaked your code so that it will put each filename into a slice of strings and then print the slice at the end. Also, keep in mind that you already have a file list in the 'files' variable.

package main

import (
  "bufio"
  "fmt"
  "os"
  "path/filepath"
  //"bytes"
  //"io/ioutil"
)

func main() {

  lineScan := bufio.NewScanner(os.Stdin)
  var inputText string

  fmt.Print("Enter file extension to search for: .extension \n")
  lineScan.Scan()
  inputText = lineScan.Text()

  dirname := "." + string(filepath.Separator)

  d, err := os.Open(dirname)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  defer d.Close()

  files, err := d.Readdir(-1)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  fileList := make([]string, 0)
  for _, file := range files { 
    if file.Mode().IsRegular() {

      if filepath.Ext(file.Name()) == inputText {

        fmt.Println(file.Name())
        fileList = append(fileList, file.Name())
      }
    }
  }

  fmt.Println("File List: ", fileList)
}

I hope this works for you.

Upvotes: 3

Related Questions