Skip to content

Instantly share code, notes, and snippets.

@voratham
Forked from minikomi/filebuffer.go
Created September 21, 2021 07:05
Show Gist options
  • Save voratham/9faa4eada5f178bcecb601c2dff846c4 to your computer and use it in GitHub Desktop.
Save voratham/9faa4eada5f178bcecb601c2dff846c4 to your computer and use it in GitHub Desktop.
Read file to buffered bytes buffer in chunks.
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"os"
)
const (
chunksize int = 1024
)
var (
data *os.File
part []byte
err error
count int
)
func openFile(name string) (byteCount int, buffer *bytes.Buffer) {
data, err = os.Open(name)
if err != nil {
log.Fatal(err)
}
defer data.Close()
reader := bufio.NewReader(data)
buffer = bytes.NewBuffer(make([]byte, 0))
part = make([]byte, chunksize)
for {
if count, err = reader.Read(part); err != nil {
break
}
buffer.Write(part[:count])
}
if err != io.EOF {
log.Fatal("Error Reading ", filename, ": ", err)
} else {
err = nil
}
byteCount = buffer.Len()
return
}
func main() {
length, _ := openFile("data.txt")
fmt.Println(length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment