-
-
Save voratham/9faa4eada5f178bcecb601c2dff846c4 to your computer and use it in GitHub Desktop.
Read file to buffered bytes buffer in chunks.
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 ( | |
"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