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
+21.3k Golang : Round float to precision example
+5.7k Golang : Muxing with Martini example
+39.7k Golang : How to check if a string contains another sub-string?
+18.1k Golang : How to run your code only once with sync.Once object
+16.1k Golang : Find smallest number in array
+14.1k Golang : Get query string value on a POST request
+28.6k Golang : How to get HTTP request header information?
+11.6k Golang : Pass database connection to function called from another package and HTTP Handler
+7.5k Golang : How to join strings?
+10.6k Golang : Handle API query by curl with Gorilla Queries example
+16.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography