go读取一个文件的所有行内容

为什么80%的码农都做不了架构师?>>>   hot3.png

package main
import(
	"os"
	"bufio"
	"fmt"
	"io"
)

func read_lines(file string)(lines []string, err error){
	fd, err := os.Open(file)
	if (err != nil){
		return
	}
	br := bufio.NewReader(fd)
	lines = make([]string, 0)
	for line_end := true;;{
		line_bytes, is_prefix, err1 := br.ReadLine()
		if (err1 != nil){
			if (err1 != io.EOF){
				err = err1
			}
			break
		}

		line := string(line_bytes)
		if (line_end == false){
			lines[len(lines) - 1] += line

		}else{
			lines = append(lines, line)
			line_end = !is_prefix
		}
	}

	return
}

func main(){
	lines, err := read_lines("/etc/passwd")
	if (err == nil){
		fmt.Println(lines)
	}else{
		fmt.Println(err)
	}
}

在golang中,ReadLine默认只读了4096的内容(go version go1.6 darwin/amd64)。但是根据ReadLine的第二个参数 is_prefix可以知道还有没有没读完的。以下是go doc对isPrefix的描述

If the line was too long for the buffer then isPrefix is set and the beginning of the line is returned.

转载于:https://my.oschina.net/tuxpy/blog/675182

你可能感兴趣的:(go读取一个文件的所有行内容)