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
+34k Golang : Call a function after some delay(time.Sleep and Tick)
+5k Python : Convert(cast) bytes to string example
+26.5k Golang : Convert(cast) string to uint8 type and back to string
+20.3k Golang : Count number of digits from given integer value
+7.8k Golang : Error reading timestamp with GORM or SQL driver
+30.6k Get client IP Address in Go
+5.5k Golang : fmt.Println prints out empty data from struct
+6.2k Golang : Extract XML attribute data with attr field tag example
+6.9k Default cipher that OpenSSL used to encrypt a PEM file
+5.3k Python : Create Whois client or function example
+19.4k Golang : Get RGBA values of each image pixel