Golang,有没有更好的方法将整数文件读入数组?

我需要将整数文件读入数组。我有与此一起工作:


package main


import (

    "fmt"

    "io"

    "os"

)


func readFile(filePath string) (numbers []int) {

    fd, err := os.Open(filePath)

    if err != nil {

        panic(fmt.Sprintf("open %s: %v", filePath, err))

    }

    var line int

    for {


        _, err := fmt.Fscanf(fd, "%d\n", &line)


        if err != nil {

            fmt.Println(err)

            if err == io.EOF {

                return

            }

            panic(fmt.Sprintf("Scan Failed %s: %v", filePath, err))


        }

        numbers = append(numbers, line)

    }

    return

}


func main() {

    numbers := readFile("numbers.txt")

    fmt.Println(len(numbers))

}

文件numbers.txt只是:


1

2

3

...

ReadFile() 似乎太长了(可能是由于处理错误)。


是否有更短/更多的Go惯用方式加载文件?


斯蒂芬大帝
浏览 310回答 3
3回答

收到一只叮咚

我会这样:package mainimport ("fmt"    "io/ioutil"    "strconv"    "strings")// It would be better for such a function to return error, instead of handling// it on their own.func readFile(fname string) (nums []int, err error) {    b, err := ioutil.ReadFile(fname)    if err != nil { return nil, err }    lines := strings.Split(string(b), "\n")    // Assign cap to avoid resize on every append.    nums = make([]int, 0, len(lines))    for i, l := range lines {        // Empty line occurs at the end of the file when we use Split.        if len(l) == 0 { continue }        // Atoi better suits the job when we know exactly what we're dealing        // with. Scanf is the more general option.        n, err := strconv.Atoi(l)        if err != nil { return nil, err }        nums = append(nums, n)    }    return nums, nil}func main() {    nums, err := readFile("numbers.txt")    if err != nil { panic(err) }    fmt.Println(len(nums))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go