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, "%dn", &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()似乎太长(可能是由于处理错误)。

有没有一种较短/较常用的加载文件的方法?

使用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 := "1n2n3n4n5n6"
    ints, err := ReadInts(strings.NewReader(tf))
    fmt.Println(ints, err)
}

我会这样做:

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

您的fmt解决方案。Fscanf很好。当然,根据你的情况,还有很多其他方法可以做。莫斯塔法的技术是我经常使用的(尽管我可能会用make一次分配结果。哎呀!他做到了。)但为了最终控制,你应该学习bufio。ReadLine。请参阅go readline->一些示例代码的字符串。

最新更新