Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
reading-files-in-go/reading-chunkwise.go
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
39 lines (32 sloc)
797 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
) | |
func main() { | |
const BufferSize = 100 | |
file, err := os.Open("filetoread.txt") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer file.Close() | |
buffer := make([]byte, BufferSize) | |
for { | |
bytesread, err := file.Read(buffer) | |
// err value can be io.EOF, which means that we reached the end of | |
// file, and we have to terminate the loop. Note the fmt.Println lines | |
// will get executed for the last chunk because the io.EOF gets | |
// returned from the Read function only on the *next* iteration, and | |
// the bytes returned will be 0 on that read. | |
if err != nil { | |
if err != io.EOF { | |
fmt.Println(err) | |
} | |
break | |
} | |
fmt.Println("bytes read: ", bytesread) | |
fmt.Println("bytestream to string: ", string(buffer[:bytesread])) | |
} | |
} |