《Hands-On System Programming with Go》之读文件

有点全,但不是很全。

一次读入,分批次读入,缓存读入。

要记得这几种不同读取的应用场景。

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Please specify a path.")
		return
	}

	b1, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println("Error: ", err)
	}

	fmt.Println(string(b1))

	f1, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Println("Error: ", err)
	}

	defer f1.Close()

	var (
		b2 = make([]byte, 16)
	)

	for n := 0; err == nil; {
		n, err = f1.Read(b2)
		if err == nil {
			fmt.Print(string(b2[:n]))
		}
	}
	for err != nil && err != io.EOF {
		fmt.Println("\n\nError: ", err)
	}

	var b3 = bytes.NewBuffer(make([]byte, 26))

	var texts = []string{
		`As he came into the window`,
		`It was the sound of a crescendo
He came into her apartment`,
		`He left the bloodstains on the carpet`,
		`She ran underneath the table
He could see she was unable
So she ran into the bedroom
She was struck down, it was her doom`,
	}

	for i := range texts {
		b3.Reset()
		b3.WriteString(texts[i])
		fmt.Println("Length: ", b3.Len(), "\tCapacity: ", b3.Cap())
	}

	f2, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Println("Error: ", err)
	}

	defer f2.Close()

	r := bufio.NewReader(f2)
	var rowCount int
	for err == nil {
		var b4 []byte
		for moar := true; err == nil && moar; {
			b4, moar, err = r.ReadLine()
			if err == nil {
				fmt.Print(string(b4))
			}
		}
		if err == nil {
			fmt.Println()
			rowCount++
		}
	}
	if err != nil && err != io.EOF {
		fmt.Println("\nError: ", err)
		return
	}
	fmt.Println("\nRow count: ", rowCount)

}

  《Hands-On System Programming with Go》之读文件

上一篇:Java 的API(API: Application(应用) Programming(程序) Interface(接口))


下一篇:Quatus II jic文件生成