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
+6.9k Golang : Experimental emojis or emoticons icons programming language
+7.8k Android Studio : AlertDialog to get user attention example
+5.4k Golang : How to deal with configuration data?
+15.4k Golang : Get timezone offset from date or timestamp
+16.6k Golang : Test floating point numbers not-a-number and infinite example
+7.2k Golang : Transform lisp or spinal case to Pascal case example
+6.1k Golang : Compound interest over time example
+11.2k Golang : Roll the dice example
+16.6k Golang : Get IP addresses of a domain name
+17k Golang : Read integer from file into array
+11.9k How to tell if a binary(executable) file or web application is built with Golang?
+9k Golang : Find network service name from given port and protocol