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
+7k Golang : Gargish-English language translator
+7.8k Golang : Get today's weekday name and calculate target day distance example
+4.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+9.4k Facebook : Getting the friends list with PHP return JSON format
+6.9k Golang : Levenshtein distance example
+4.8k Javascript : How to get width and height of a div?
+4.5k Javascript : Detect when console is activated and do something about it
+7.2k Golang : alternative to os.Exit() function
+15.2k Golang : How to get Unix file descriptor for console and file
+7.6k Golang : Convert(cast) io.Reader type to string
+17k Golang : Get input from keyboard
+6.5k PHP : Shuffle to display different content or advertisement