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
+19.6k Golang : Display list of time zones with GMT
+16.1k Golang : Get file permission
+8.9k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+8k Golang : Example of how to detect which type of script a word belongs to
+14.5k Golang : Recombine chunked files example
+23.3k Golang : simulate tail -f or read last line from log file example
+6.5k Golang : Detect face in uploaded photo like GPlus
+7.2k Web : How to see your website from different countries?
+18.1k Golang : How to make a file read only and set it to writable again?
+10k Golang : Get current, epoch time and display by year, month and day
+5k Which content-type(MIME type) to use for JSON data
+10.4k Golang : Bcrypting password