在Golang中,如何将循环的结果添加到一个未知大小的动态数组中?

huangapple go评论71阅读模式
英文:

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

问题

我现在是你的中文翻译。以下是你要翻译的内容:

我现在正在处理的示例从控制台获取输入,询问文件扩展名,比如 .txt。它在当前目录中搜索文件,然后使用Println将所有具有 .txt 扩展名的文件返回到屏幕上。

对于返回的每个结果,我该如何将每个文件名放入一个数组(或切片)中,然后在程序的后面访问每个值以操作每个文件。

它不需要是顺序的。

这是工作中的代码(修改自Adam Ng,我想):

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "bufio"
)

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)
    }

    var filenames []string

    for _, file := range files {
        if file.Mode().IsRegular() {
            if filepath.Ext(file.Name()) == inputText {
                fmt.Println(file.Name())
                filenames = append(filenames, file.Name())
            }
        }
    }

    // 在这里可以使用 filenames 数组进行后续操作
}

在这个修改后的代码中,我添加了一个名为filenames的字符串切片,用于存储符合条件的文件名。在每次找到符合条件的文件名时,我使用append函数将其添加到filenames切片中。你可以在程序的后续部分使用filenames切片来操作每个文件名。

英文:

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())
              }
          }
      }
  }

答案1

得分: 3

我调整了你的代码,使其将每个文件名放入一个字符串切片中,然后在最后打印该切片。另外,请记住,你已经在'files'变量中有一个文件列表。

package main

import (
  "bufio"
  "fmt"
  "os"
  "path/filepath"
)

func main() {

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

  fmt.Print("输入要搜索的文件扩展名:.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("文件列表:", fileList)
}

希望这对你有用。

英文:

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.

huangapple
  • 本文由 发表于 2017年1月12日 02:25:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/41598062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定