Bufio.ScanBytes
Suppose in Go we want to read each individual byte
in a file. We can test, store or append (to a byte slice) each byte
.
NewScanner
With bufio.NewScanner
, we can call Split
with an argument of bufio.ScanBytes
. Then we call Scan
and Bytes()
to read each byte
.
To begin, we include the "bufio" and "os" packages to make sure our program will compile. We then use os.Open
on the file path.
bufio.NewScanner
method—we pass in the file descriptor.Split()
sets the "splitting" method that controls how Scan()
behaves. We use the built-in method ScanBytes
on bufio.for
-loop that calls Scan()
. We call Bytes()
on each iteration, which returns a 1-byte slice with the byte
that was read.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`) }[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
When we execute this program, it reads in the specified file. The file used in the example contains the strings "Thank you Friend."
To create a byte slice containing the file data, we could append to an empty byte slice. This approach can be helpful if we need to test each individual byte
as we read the file.