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

前端 未结 3 1193
無奈伤痛
無奈伤痛 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:58

    Using a bufio.Scanner makes things nice. I've also used an io.Reader rather than taking a filename. Often that's a good technique, since it allows the code to be used on any file-like object and not just a file on disk. Here it's "reading" from a string.

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "strconv"
        "strings"
    )
    
    // ReadInts reads whitespace-separated ints from r. If there's an error, it
    // returns the ints successfully read so far as well as the error value.
    func ReadInts(r io.Reader) ([]int, error) {
        scanner := bufio.NewScanner(r)
        scanner.Split(bufio.ScanWords)
        var result []int
        for scanner.Scan() {
            x, err := strconv.Atoi(scanner.Text())
            if err != nil {
                return result, err
            }
            result = append(result, x)
        }
        return result, scanner.Err()
    }
    
    func main() {
        tf := "1\n2\n3\n4\n5\n6"
        ints, err := ReadInts(strings.NewReader(tf))
        fmt.Println(ints, err)
    }
    

提交回复
热议问题