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
+5.6k Golang : Skip or discard items of non-interest when iterating example
+8.8k Golang : Translate language with language package example
+12.3k Golang : Verify token from Google Authenticator App
+9.2k Golang : How to profile or log time spend on execution?
+5.8k Mac/Linux/Windows : Get CPU information from command line
+35.3k Golang : Convert(cast) int64 to string
+15.6k Golang : Get own process identifier
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+20.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+8.8k PHP : Get coordinates latitude/longitude from string
+12.1k Golang : Image to ASCII art example
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface