Golang,有没有更好的方法将整数文件读入数组? [英] Golang, is there a better way read a file of integers into an array?

查看:626
本文介绍了Golang,有没有更好的方法将整数文件读入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将整数文件读入数组中。

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 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只是:

The file numbers.txt is just:

1
2
3
...

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

ReadFile() seems too long (maybe because of the error handing).

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

Is there a shorter / more Go idiomatic way to load a file?

推荐答案

使用 bufio.Scanner 使事情变得更好。我还使用了 io.Reader ,而不是使用文件名。通常这是一种很好的技术,因为它允许将代码用于任何类似文件的对象而不仅仅是磁盘上的文件。

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

这篇关于Golang,有没有更好的方法将整数文件读入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆