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
+9.1k Golang : Embed secret text string into binary(executable) file
+25.5k Golang : How to check if a connection to database is still alive ?
+8.2k Golang : Detect number of active displays and the display's resolution
+15.4k CodeIgniter/PHP : Create directory if does not exist example
+18.3k Golang : Archive directory with tar and gzip
+9.8k Golang : Removes punctuation or defined delimiter from the user's input
+4.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+10.4k Golang : Secure file deletion with wipe example
+3.8k Linux : How to set root password in Linux Mint
+23.9k Golang : Convert uint value to string type
+5.5k Golang : Find the longest line of text example
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character