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

时间:2012-03-25 17:41:54

标签: go

我需要将一个整数文件读入一个数组。我有这个工作:

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惯用方法来加载文件?

3 个答案:

答案 0 :(得分:17)

使用bufio.Scanner会让事情变得更好。我还使用了io.Reader而不是文件名。通常这是一种很好的技术,因为它允许代码在任何类文件对象上使用,而不仅仅是磁盘上的文件。这是从字符串中“读取”。

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

答案 1 :(得分:5)

我会这样做:

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

答案 2 :(得分:0)

使用fmt.Fscanf的解决方案很好。根据您的具体情况,肯定还有很多其他方法可以做。 Mostafa的技术是我经常使用的技术(虽然我可以用make.oops同时分配结果!刮擦它。他做了。)但是为了最终控制你应该学习bufio.ReadLine。有关示例代码,请参阅go readline -> string