The ability to read files is a building block for any non-trivial program. Hence, any programmer must learn how to read files.

You will have the fundamental skills to read file contents using the Go programming language by the end of this article.

Open File For Reading

The first method when reading any file is opening it. To open a file in Go, we can use the Open() or OpenFile() methods from the os package.

For simplicity, we will stick to the Open() method.

The code below shows the syntax for opening a file using the os package:

file, err := os.Open(“filename”)

For example, to open a file called “hello.txt” in the current working directory, we can do:

file, err := os.Open(“hello.txt”)

It is also good to close the file after completing the required operations. We can close the file using the close method as:

Ensure any operation you perform on the file is located under the open() and close() method.

Golang Read File.

We can use various methods and techniques to read a file in Go. Let us discuss some common and most efficient ones.

Read Entire File.

The most common and simplistic method of reading files is to use the ReadFile method from the ioutil package. This method will read the entire file and store it as a large string.

Despite its simplistic nature, this method is not very efficient when it comes to working with large files.

Let us use an example to illustrate working with the ReadFile() method.

Start by creating a file called “hello.txt” in your current working directory.

Next, edit the file with your text editor and add the following:

$ vim hello.txt

> Hello from hello.txt

Close and save the file.

Now we can use the ReadFile() method to read the content of the entire file as:

package main


import (


    “fmt”


    “io/ioutil”


    “log”

)


func main() {


    data, err := ioutil.ReadFile(“hello.txt”)


    if err != nil {


        log.Fatal(err)


    }


    fmt.Println(string(data))

}

The program above will read the file and print its content to the console. Note that we need to convert the data into a string before printing it out. Otherwise, you will get a slice of characters.

Read File by Chunks

Another way to read a file in Go is to read it in chunks. This means we do not load the entire contents into memory but instead chop off small sections.

This can be a very good technique when working with large files.

For example:

package main


import (


    “bufio”


    “fmt”


    “io”


    “log”


    “os”

)


func main() {


    file, err := os.Open(“hello.txt”)


    if err != nil {


        log.Fatal(err)


    }


    defer file.Close()


    reader := bufio.NewReader(file)


    buffer := make([]byte, 8)


    for {


        read, err := reader.Read(buffer)


        if err != nil {


            if err != io.EOF {


                log.Fatal(err)


            }


            break


        }


        fmt.Println(string(buffer[:read]))


    }

}

In the example above, we read the file into chunks of 8 bytes. We read the data into the buffer using the Read method using a for a loop. Finally, we print the array buffer using the Println() method.

The resulting chunks of data read are as shown:

$ go run <filename.go>


Hello fr


om the h


ello.txt


 file

Read file line by line

We can also read files line by line using the bufio package. An example is as shown below:

package main


import (


    “bufio”


    “fmt”


    “log”


    “os”

)


func main() {


    file, err := os.Open(“hello.txt”)


    if err != nil {


        log.Fatal(err)


    }


    defer file.Close()


    scanner := bufio.NewScanner(file)


    for scanner.Scan() {


        fmt.Println(scanner.Text())


    }


    if err := scanner.Err(); err != nil {


        log.Fatal(err)


    }

}

The scanner will scan the line and print a new line anytime it encounters the n character.

Read File Word by Word

We can also use the ScanWord method from the bufio package to read the file word by word. An example code is as shown:

package main


import (


    “bufio”


    “fmt”


    “log”


    “os”

)


func main() {


    file, err := os.Open(“hello.txt”)


    if err != nil {


        log.Fatal(err)


    }


    defer file.Close()


    scanner := bufio.NewScanner(file)


    scanner.Split(bufio.ScanWords)


    for scanner.Scan() {


        fmt.Println(scanner.Text())


    }


    if err := scanner.Err(); err != nil {


        log.Fatal(err)


    }

}

In the example above, we scan the file word by word using the ScanWords provided by the bufio package.

The resulting output is as:

Hello


from


the


hello.txt

file

Conclusion

This guide discusses common methods and techniques to read files in the go programming language.

Keep coding!!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352b4d0fc6.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list