Home
Go
bufio.ScanBytes, NewScanner (Read Bytes in File)
Updated Mar 27, 2023
Dot Net Perls
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.
An example. 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.
Start We create a new scanner with the bufio.NewScanner method—we pass in the file descriptor.
Important Split() sets the "splitting" method that controls how Scan() behaves. We use the built-in method ScanBytes on bufio.
Here 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.
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
Notes, results. When we execute this program, it reads in the specified file. The file used in the example contains the strings "Thank you Friend."
And We see the ASCII representation of the file contents. The space and newline are also included.
A review. 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.
File Lines
File
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 27, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen