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.1k Android Studio : How to detect camera, activate and capture example
+13k Android Studio : Password input and reveal password example
+15.4k Golang : How to login and logout with JWT example
+11.8k Golang : Save webcamera frames to video file
+13.2k Golang : Get user input until a command or receive a word to stop
+8.8k Golang : Simple histogram example
+5.8k PageSpeed : Clear or flush cache on web server
+5.5k Unix/Linux : Get reboot history or check when was the last reboot date
+7.8k Golang : Variadic function arguments sanity check example
+22.8k Golang : Get ASCII code from a key press(cross-platform) example
+17.3k Golang : Defer function inside init()