What is Golang ioutil?

ioutil is a Golang (Go) package that provides I/O utility functions. It is often used with the OS package to provide additional methods of handling I/O, like files.

Syntax

Syntax What it does
func ReadFile(filename string) ([]byte, error) Reads the file named by filename and returns the contents.
func ReadAll(r io.Reader) ([]byte, error) Reads from the io.Reader r until an error or EOF, then it returns the content.
func ReadDir(dirname string) ([]os.FileInfo, error) Reads the directory named by dirname and returns a list of directory entries sorted by filename.
func TempFile(dir, pattern string) (f *os.File, err error) Creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File.
func TempDir(dir, pattern string) (name string, err error) Creates a new temporary directory in the directory dir.
func WriteFile(filename string, data []byte, perm os.FileMode) error Writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise, WriteFile truncates it before writing.

Example

In the example below, we use ReadFile to read a file and print its content. We then use WriteFile to create and write to a new file. Finally, we read and print all the files in the current directory.

main.go
example.txt
package main
import (
"fmt"
"io/ioutil"
)
// Helper function for logging errors
func check(err error) {
if err != nil {
panic(err)
}
}
func main() {
// Reading content from file.
content, err := ioutil.ReadFile("example.txt")
check(err)
fmt.Printf("File contents: %s\n", content)
// Writing to a new file newFile.txt.
data := []byte("Hello, Educative!")
err = ioutil.WriteFile("newFile.txt", data, 0644)
check(err)
// Printing all files in the current directory.
// Notice a new newFile.txt file (that we created above).
files, err := ioutil.ReadDir(".")
check(err)
fmt.Println("Files in the current directory:")
for _, file := range files {
fmt.Println(file.Name())
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved