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

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《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("

Error: ", 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(), "	Capacity: ", 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("
Error: ", err)
		return
	}
	fmt.Println("
Row count: ", rowCount)

}

  技术图片

以上是关于《Hands-On System Programming with Go》之读文件的主要内容,如果未能解决你的问题,请参考以下文章

Wireshark Hands-on Assignmen

DRL Hands-on book

在本地设置 Programm-o

2017.11.12 Power BI hands-on lab workshop

Hands-on data analysis 第一章

Hands-on data analysis 第一章