golang 一行一行读文件

前端之家收集整理的这篇文章主要介绍了golang 一行一行读文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
        "bufio"
        "fmt"
        "os"
)
func main() {
        counts := make(map[string]int)
        files := os.Args[1:]
        if len(files) == 0 {
                countLines(os.Stdin,counts)
        } else {
                for _,arg := range files {
                        f,err := os.Open(arg)
                        if err != nil {
                                fmt.Fprintf(os.Stderr,"dup2: %v\n",err)
                                continue
                        }
                        countLines(f,counts)
                        f.Close()
                }
        }
        for line,n := range counts {
                fmt.Printf("%d\t%s\n",n,line)
        }
}

func countLines(f *os.File,counts map[string]int) {
        input := bufio.NewScanner(f)
        for input.Scan() {
                counts[input.Text()]++
        }
        // NOTE: ignoring potential errors from input.Err()
}


go run main.go a.txt


另一种方法

package main

import (
	"fmt"
	"io/IoUtil"
	"os"
	"strings"
)

func main() {
	counts := make(map[string]int)
	for _,filename := range os.Args[1:] {
		data,err := IoUtil.ReadFile(filename)
		if err != nil {
			fmt.Fprintf(os.Stderr,"dup3: %v\n",err)
			continue
		}
		for _,line := range strings.Split(string(data),"\n") {
			counts[line]++
		}
	}
	for line,n := range counts {
		if n > 1 {
			fmt.Printf("%d\t%s\n",line)
		}
	}
}
原文链接:https://www.f2er.com/go/188683.html

猜你在找的Go相关文章