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
+8.2k Golang : Generate EAN barcode
+8.9k Golang : Resumable upload to Google Drive(RESTful) example
+12.3k Golang : Linear algebra and matrix calculation example
+22.3k Find and replace a character in a string in Go
+6k Mac OSX : Find large files by size
+9.2k Golang : Channels and buffered channels examples
+20.3k Golang : Encrypt and decrypt data with TripleDES
+6.1k Golang : Calculate BMI and risk category
+5.8k Nginx : Password protect a directory/folder
+16.3k Golang : Get future or past hours, minutes or seconds
+7.9k Golang : Gaussian blur on image and camera video feed examples
+18.7k Golang : Count JSON objects and convert to slice/array