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
+7.3k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+8.5k Golang : interface - when and where to use examples
+12.6k Android Studio : Use image as AlertDialog title with custom layout example
+17.6k Golang : Read input from console line
+8.2k Golang : How to generate Code 39 barcode?
+38k Golang : UDP client server read write example
+2.9k Golang : PGX CopyFrom to insert rows into Postgres database
+10.2k Golang : GTK Input dialog box examples
+15.5k Golang : Get own process identifier
+10.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+7.9k Golang : Go as a script or running go with shebang/hashbang style
+7.8k Golang : HTTP Routing with Goji example