golang-101-hacks(25)——Buffered read

羊羽shine · · 623 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

bufio包提供缓冲读取的函数。如下面例子所示

(1) 首先创建test.txt
(1) Create a test.txt file first:

# cat test.txt
abcd
efg
hijk
lmn

You can see test.txt contains 4 lines.

(2) See the following program:

package main

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

func main() {
        f, err := os.Open("test.txt")
        if err != nil {
                log.Fatal(err)
        }

        r := bufio.NewReader(f)
        for {
                if s, err := r.ReadSlice('\n'); err == nil || err == io.EOF {
                        fmt.Printf("%s", s)
                        if err == io.EOF {
                                break
                        }
                } else {
                        log.Fatal(err)
                }

        }
}

(a)

f, err := os.Open("test.txt")

Open test.txt file.

(b)

r := bufio.NewReader(f)

bufio.NewReader(f) creates a bufio.Reader struct which implements buffered read function.

(c)

for {
    if s, err := r.ReadSlice('\n'); err == nil || err == io.EOF {
        fmt.Printf("%s", s)
        if err == io.EOF {
            break
        }
    } else {
        log.Fatal(err)
    }

}

Read and print each line.

The running result is here:

abcd
efg
hijk
lmn

We can also use bufio.Scanner to implement above "print each line" function:

package main

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

func main() {
        f, err := os.Open("test.txt")
        if err != nil {
                log.Fatal(err)
        }

        s := bufio.NewScanner(f)

        for s.Scan() {
                fmt.Println(s.Text())
        }
}

(a)

s := bufio.NewScanner(f)

bufio.NewScanner(f) creates a new bufio.Scanner struct which splits the content by line by default.

(b)

for s.Scan() {
    fmt.Println(s.Text())
}

s.Scan() advances the bufio.Scanner to the next token (in this case, it is one optional carriage return followed by one mandatory newline), and we can use s.Text() function to get the content.

We can also customize SplitFunc function which doesn't separate content by line. Check the following code:

package main

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

func main() {
        f, err := os.Open("test.txt")
        if err != nil {
                log.Fatal(err)
        }

        s := bufio.NewScanner(f)
        split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
                for i := 0; i < len(data); i++ {
                        if data[i] == 'h' {
                                return i + 1, data[:i], nil
                        }
                }

                return 0, data, bufio.ErrFinalToken
        }
        s.Split(split)
        for s.Scan() {
                fmt.Println(s.Text())
        }
}

The split function separates the content by "h", and the running result is:

abcd
efg

ijk
lmn

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:羊羽shine

查看原文:golang-101-hacks(25)——Buffered read

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

623 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传