Home
Search
bufio.ScanBytes, NewScanner (Read Bytes in File)Use bufio.NewScanner and Split with ScanBytes to read each byte in a file.
Golang
This page was last reviewed on Dec 20, 2022.
Bufio.ScanBytes. Suppose 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.
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.
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.
Get Lines in File
File
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.