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
+21k Golang : How to force compile or remove object files first before rebuild?
+5.6k List of Golang XML tutorials
+12.1k Golang : List running EC2 instances and descriptions
+5.8k Golang : Shuffle array of list
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+5.3k Golang : Intercept, inject and replay HTTP traffics from web server
+13.3k Golang : Get constant name from value
+10.1k Golang : How to profile or log time spend on execution?
+41.3k Golang : Convert string to array/slice
+11.8k Golang : Determine if time variables have same calendar day
+26.2k Golang : Convert(cast) string to uint8 type and back to string
+4.6k MariaDB/MySQL : How to get version information