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
+7.2k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+5.8k Java : Human readable password generator
+8.9k Golang : How to control fmt or log print format?
+12.2k Golang : Sort and reverse sort a slice of bytes
+12.2k Swift : Convert (cast) Int or int32 value to CGFloat
+4.1k Linux/MacOSX : Search and delete files by extension
+5.7k Golang : Experimenting with the Rejang script
+5.8k Golang : Create new color from command line parameters
+6.6k Golang : Gargish-English language translator
+7.4k Golang : How to execute code at certain day, hour and minute?
+9.9k Golang : How to profile or log time spend on execution?
+15.7k Golang : How to check if input from os.Args is integer?