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
+21.1k Golang : Generate MD5 checksum of a file
+6.8k Android Studio : Image button and button example
+19.3k Golang : For loop continue,break and range
+9.4k Golang : Web routing/multiplex example
+7k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+4.1k Golang : How to deal with configuration data?
+8.4k Golang : Check a web page existence with HEAD request example
+8k Golang : Quadratic example
+4.6k Golang : Launching your executable inside a console under Linux
+9.6k Golang : How to pipe input data to executing child process?
+6.5k Golang : Test if an input is an Armstrong number example
+26.5k Golang : Detect (OS) Operating System