Go Package bufio: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 9: Line 9:


=Reading a Text File Line by Line=
=Reading a Text File Line by Line=
==With <tt>Scanner</tt>==
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
import (
import (
Line 27: Line 28:
}
}
</syntaxhighlight>
</syntaxhighlight>
==With <tt>Reader</tt>==

Revision as of 21:08, 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