Go Package bufio: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=External= * https://pkg.go.dev/bufio =Internal= * Standard Library =Overview= =Reading a Text File Line by Line=")
 
 
(6 intermediate revisions by the same user not shown)
Line 3: Line 3:
=Internal=
=Internal=
* [[Go_Language_Modularization#bufio|Standard Library]]
* [[Go_Language_Modularization#bufio|Standard Library]]
* [[File_Operations_in_Go#Line_by_Line|File Operations in Go]]
=Overview=
=Overview=
The <code>bufio</code> package is aimed at buffering input in something faster (memory) while interacting with something slower (disk). <code>bufio</code> is useful in situations when [[Queueing_Theory#Queueing_and_Overall_Pipeline_Performance|queueing improves the overall system performance]].
=Reading a Text File Line by Line=
=Reading a Text File Line by Line=
==With <tt>Scanner</tt>==
<syntaxhighlight lang='go'>
import (
"bufio"
"os"
)
f, err := os.Open("/Users/ovidiu/tmp/sometext.txt")
if err != nil {
  ...
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
  line := scanner.Text()
  ...
}
</syntaxhighlight>
==With <tt>Reader</tt>==
<code>ReadLine()</code> returns <code>[[Go_Package_io#io.EOF|io.EOF]]</code> on end of file.
<syntaxhighlight lang='go'>
f, err := os.Open(...)
r := bufio.NewReader(f)
for {
lineb, _, err := r.ReadLine()
if err != nil {
if errors.Is(err, io.EOF) {
fmt.Printf("is End of File!\n")
        } else {
    fmt.Printf("%v\n", err)
}
break
} else {
fmt.Printf("%s\n", string(lineb))
}
}
</syntaxhighlight>

Latest revision as of 21:22, 29 February 2024

External

Internal

Overview

The bufio package is aimed at buffering input in something faster (memory) while interacting with something slower (disk). bufio is useful in situations when queueing improves the overall system performance.

Reading a Text File Line by Line

With Scanner

import (
	"bufio"
	"os"
)

f, err := os.Open("/Users/ovidiu/tmp/sometext.txt")
if err != nil {
  ...
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
  line := scanner.Text()
  ...
}

With Reader

ReadLine() returns io.EOF on end of file.

f, err := os.Open(...)
r := bufio.NewReader(f)
for {
	lineb, _, err := r.ReadLine()
	if err != nil {
		if errors.Is(err, io.EOF) {
			fmt.Printf("is End of File!\n")
        } else {
		    fmt.Printf("%v\n", err)
		}
		break
	} else {
		fmt.Printf("%s\n", string(lineb))
	}
}