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
+36.1k Golang : Validate IP address
+7.3k Gogland : Single File versus Go Application Run Configurations
+15.3k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+30.6k error: trying to remove "yum", which is protected
+6.5k Golang : Output or print out JSON stream/encoded data
+5.6k Golang : Launching your executable inside a console under Linux
+17.3k Golang : [json: cannot unmarshal object into Go value of type]
+7k Golang : Of hash table and hash map
+12.3k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+7.8k Golang : Handle Palindrome string with case sensitivity and unicode
+6.6k How to let Facebook Login button redirect to a particular URL ?
+7.2k Golang : Convert source code to assembly language