Read text file into string array (and write)

前端 未结 5 846
-上瘾入骨i
-上瘾入骨i 2020-12-07 08:44

The ability to read (and write) a text file into and out of a string array is I believe a fairly common requirement. It is also quite useful when starting with a language re

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 09:24

    As of Go1.1 release, there is a bufio.Scanner API that can easily read lines from a file. Consider the following example from above, rewritten with Scanner:

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    // readLines reads a whole file into memory
    // and returns a slice of its lines.
    func readLines(path string) ([]string, error) {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }
        defer file.Close()
    
        var lines []string
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            lines = append(lines, scanner.Text())
        }
        return lines, scanner.Err()
    }
    
    // writeLines writes the lines to the given file.
    func writeLines(lines []string, path string) error {
        file, err := os.Create(path)
        if err != nil {
            return err
        }
        defer file.Close()
    
        w := bufio.NewWriter(file)
        for _, line := range lines {
            fmt.Fprintln(w, line)
        }
        return w.Flush()
    }
    
    func main() {
        lines, err := readLines("foo.in.txt")
        if err != nil {
            log.Fatalf("readLines: %s", err)
        }
        for i, line := range lines {
            fmt.Println(i, line)
        }
    
        if err := writeLines(lines, "foo.out.txt"); err != nil {
            log.Fatalf("writeLines: %s", err)
        }
    }
    

提交回复
热议问题