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
+10.6k Golang : Get UDP client IP address and differentiate clients by port number
+5.7k Golang : Shuffle array of list
+10.3k Golang : How to delete element(data) from map ?
+7.4k Golang : Command line ticker to show work in progress
+5.2k Golang : fmt.Println prints out empty data from struct
+17.3k Golang : delete and modify XML file content
+12.3k Golang : HTTP response JSON encoded data
+17.3k Golang : Upload/Receive file progress indicator
+32.5k Golang : How to check if a date is within certain range?
+12.3k Golang : Exit, terminating or aborting a program
+11.3k CodeIgniter : Import Linkedin data
+13.8k Golang : Fix image: unknown format error