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
+17.9k Golang : How to log each HTTP request to your web server?
+14.5k Golang : How to get URL port?
+10k Golang : Get login name from environment and prompt for password
+5.1k Golang : Customize scanner.Scanner to treat dash as part of identifier
+14.3k Golang : On enumeration
+5.9k Golang : Extract unicode string from another unicode string example
+6.3k Golang : How to search a list of records or data structures
+10.2k Golang : Embed secret text string into binary(executable) file
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+7k Golang : A simple forex opportunities scanner
+30.2k Golang : How to verify uploaded file is image or allowed file types
+5.6k List of Golang XML tutorials