Golang : Read file
This is the most basic way of how to read a file into buffer and display its content chunk by chunk. This example read plain text file, if you are reading a binary file... change fmt.Println(string(buffer[:n]))
to fmt.Println(buffer[:n])
(without the string).
For now, this is the most basic example of reading a file in Go
package main
import (
"fmt"
"io"
"os"
)
func main() {
file, err := os.Open("sometextfile.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// create a buffer to keep chunks that are read
buffer := make([]byte, 1024)
for {
// read a chunk
n, err := file.Read(buffer)
if err != nil && err != io.EOF { panic(err) }
if n == 0 { break }
// out the file content
fmt.Println(string(buffer[:n]))
}
}
See also : Golang : How to read CSV file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.8k Golang : reCAPTCHA example
+3.4k Golang : Generate random Chinese, Japanese, Korean and other runes
+4.4k Golang : Gomobile init produce "iphoneos" cannot be located error
+3.2k Golang : Build and compile multiple source files
+5.5k Golang : Convert file unix timestamp to UTC time example
+7.1k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+14.5k Golang : How to get time zone and load different time zone?
+26.9k Golang : Read tab delimited file with encoding/csv package
+2.8k AWS S3 : Prevent Hotlinking policy
+6.2k Golang : Generate Code128 barcode
+4.2k Golang : Heap sort example
+2.8k Golang : Compound interest over time example