golang

Golang ioutil

The ioutil package in Go is used to provide I/O functions. It is a handy package when you need to work with files.

In this article, we will explore some useful methods and functionalities implemented by the ioutil package.

Required Imports

The ioutil package is part of the Go standard library. However, we need to import it before use. You can do this by adding an import clause as:

import "ioutil"

Ioutil.ReadAll()

The first method we can use from the ioutil package is the ReadAll() method. The function syntax is as shown:

func ReadAll(r io.Reader) ([]byte, error)

The function will read from the io.Reader r until the End of File (EOF) or an error is encountered. The function will then return the content read from the io.Reader.

We can illustrate how to use the ReadAll() method as shown in the code below:

package main
import (
    "fmt"
    "io/ioutil"
    "log"
    "strings"
)
func main() {
    r := strings.NewReader("This is a simple string")
    b, err := ioutil.ReadAll(r)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}

In the example above, we use the ReadAll() method to read the io.Reader r created using the NewReader() method.

The function should return a slice of bytes which we can convert back to a string using the strings method.

The code above should return an output as:

This is a simple string

We can also use the ReadAll() method to read a file as shown in the code below:

package main
import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)
func main() {
    file, err := os.Open("hello.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    content, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(content))
}

In the example above, we use the ReadAll() method to read a file as specified in the os.Open() method.

Ioutil.ReadFile()

The ReadFile() method reads the file as specified and return the file content. An example code is as shown:

data, err := ioutil.ReadFile("hello.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

In the example above, we use the ReadFile() method to read the “hello.txt” file and return the content.

Ioutil.ReadDir()

Another useful method from the ioutil package is the ReadDir() method. The function syntax is as shown below:

func ReadDir(dirname string) ([]fs.FileInfo, error)

The function takes the directory name as a string and returns a list of directory entries sorted by the filename.

An example code is as shown:

ls, err := ioutil.ReadDir(".")
if err != nil {
    log.Fatal(err)
}
for _, ls := range ls {
    fmt.Println(ls.Name())
}

The example uses the ReadDir() to get the list of files in the current directory. We then use a variable ls to store the result. Finally, we set a for loop with the range operator to list individual items.

An example output is as shown:

hello.txt
ioutil.go

Ioutil.WriteFile()

Another useful method from the ioutil package is the WriteFile() method. This method writes the data to the specified file. If the file does not exist, the WriteFile() method will create it using the perm and truncate it before write.

The function syntax is as shown:

func WriteFile(filename string, data []byte, perm fs.FileMode) error

An example code shows how to write to a file using the WriteFile Method.

write_this := []byte("A new entry in the file")
err := ioutil.WriteFile("hello.txt", write_this, 0644)
if err != nil {
    log.Fatal(err)
}

The above code uses the WriteFile() to write a sequence of bytes to the specified file. If the file does not exist, the function will create it with the permission 0644.

Conclusion

In this article, we cover how utilize various methods and operations provided by the ioutil package. You can check the documentation to learn more.

Thanks for reading & Happy coding!

About the author

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