C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
NewScanner: We create a new scanner with the bufio.NewScanner method—we pass in the file descriptor.
Split: This sets the "splitting" method that controls how Scan() behaves. We use the built-in method ScanBytes on bufio.
For: We use a for-loop that calls Scan(). We call Bytes() on each iteration, which returns a 1-byte slice with the byte that was read.
Golang program that uses bufio.NewScanner, Split, ScanBytes
package main
import (
"bufio"
"fmt"
"os"
)
func BytesInFile(fileName string) {
f, _ := os.Open(fileName)
scanner := bufio.NewScanner(f)
// Call Split to specify that we want to Scan each individual byte.
scanner.Split(bufio.ScanBytes)
// Use For-loop.
for scanner.Scan() {
// Get Bytes and display the byte.
b := scanner.Bytes()
fmt.Printf("%v = %v = %v\n", b, b[0], string(b))
}
}
func main() {
BytesInFile(`C:\programs\file.txt`)
}
Output
[84] = 84 = T
[104] = 104 = h
[97] = 97 = a
[110] = 110 = n
[107] = 107 = k
[32] = 32 =
[121] = 121 = y
[111] = 111 = o
[117] = 117 = u
[10] = 10 =
[70] = 70 = F
[114] = 114 = r
[105] = 105 = i
[101] = 101 = e
[110] = 110 = n
[100] = 100 = d
And: We see the ASCII representation of the file contents. The space and newline are also included.