GO语言根据空格切片输出文件中的每一行

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

func ReadLine(fileName string, handler func(string)) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		handler(line)
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}

func split(s rune) bool  {
	if s == ' ' {
		return true
	}
	return false
}

func Print(line string) {
	ip_addr := strings.FieldsFunc(line, split)[0]
	host_name := strings.FieldsFunc(line, split)[1]
	fmt.Println(ip_addr + ":" + host_name)
}

func main() {
	ReadLine("1.txt", Print)
}

  

posted @ 2018-09-11 00:20  SMALL-D  阅读(667)  评论(0编辑  收藏  举报