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 Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+21.4k Golang : Clean up null characters from input data
+13.1k Golang : Calculate elapsed years or months since a date
+7.2k Golang : A simple forex opportunities scanner
+7.2k Nginx : How to block user agent ?
+15k Golang : Basic authentication with .htpasswd file
+7.4k Golang : How to iterate a slice without using for loop?
+12.1k Golang : Clean formatting/indenting or pretty print JSON result
+13.4k Golang : Date and Time formatting
+5.3k Golang : Experimental Jawi programming language
+6.2k PageSpeed : Clear or flush cache on web server