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
+50.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+25.1k Golang : Storing cookies in http.CookieJar example
+11.8k Golang : Determine if time variables have same calendar day
+5.2k Golang : Get FX sentiment from website example
+34.9k Golang : Upload and download file to/from AWS S3
+7.6k Golang : Lock executable to a specific machine with unique hash of the machine
+13.3k Golang : Count number of runes in string
+12.6k Swift : Convert (cast) Int or int32 value to CGFloat
+5k Golang : Issue HTTP commands to server and port example
+27.7k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+9.2k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+8.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example