Go处理命令行或文件输入

462 阅读1分钟

Go 通过命令行参数处理输入,或者读取文件作为输入。

输入参数作为文件名,通过Open打开或者File类型的指针,让后bufio.NewScanner()作为输入。scanner调用scan来获取文件内容,直到文件结尾。

下面的printf

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	counts := make(map[string]int)
	files := os.Args[1:]

	if len(files) > 0 {
		for _, f := range files {
			fHandler, err := os.Open(f)
			defer fHandler.Close()
			if err != nil {
				fmt.Fprintf(os.Stderr, "Failed to open file %s: [%s]\n", f, err)
				continue
			}
			countLines(fHandler, counts)
		}

	} else {
		countLines(os.Stdin, counts)
	}

	printCounts(counts)

}

func countLines(f *os.File, counts map[string]int) {
	input := bufio.NewScanner(f)
	for input.Scan() {
		line := input.Text()
		fmt.Println(line)
		counts[line]++
	}
}

func printCounts(counts map[string]int) {
	for k, v := range counts {
		if v > 1 {
			fmt.Printf("%d: %s\n", v, k)
		}
	}
}