Golang Read File

Last Updated: September 13, 2022

Files in the GO are represented by pointers

These pointers are the objects of type os.File

You can use bufio.NewReader(inputFile) to read the file.

package main
import (“bufio” “fmt” “io” “os”)
func main() {
inputFile, inputError := os.Open(“input.dat”)
if inputError != nil {
fmt.Printf(“An error occurred on opening the inputfile\n” +
   “Does the file exist?\n” +
   “Have you got access to it?\n”)
return // exit the function on error
defer inputFile.Close()
inputReader := bufio.NewReader(inputFile)
for {
inputString, readerError := inputReader.ReadString(‘\n’)
if readerError == io.EOF {
fmt.Printf(“File has content: %s”, inputString)