Golang, is there a better way read a file of integers into an array?

前端 未结 3 1162
無奈伤痛
無奈伤痛 2021-02-04 05:01

I need to read a file of integers into an array. I have it working with this:

package main

import (
    \"fmt\"
    \"io\"
    \"os\"
)

func readFile(filePath         


        
3条回答
  •  迷失自我
    2021-02-04 05:57

    I would do it like this:

    package main
    
    import (
    "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))
    }
    

提交回复
热议问题