Go File Handling Basics

Glitch
3 min readMar 27, 2023

--

Working with files is an essential part of any programming language, and Go makes it easy and efficient to work with files. In this blog post, we will discuss the basics of working with files in Go and explore some of the standard library functions that make file handling straightforward.

File handling in Go is done using the os package. The os package provides a set of functions for creating, opening, reading, writing, and closing files. Let's take a look at some of the commonly used functions:

Creating a file

To create a new file in Go, we can use the Create function from the os package. This function takes the name of the file as the first parameter and returns a file object and an error object. Here is an example:

file, err := os.Create("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
The Create function creates a new file with the specified name in the current directory. In the example above, we create a file named "example.txt" and assign the returned file object to the file variable. We also use the defer statement to ensure that the file is closed after we are done using it.

Opening a file

To open an existing file in Go, we can use the Open function from the os package. This function takes the name of the file as the first parameter and returns a file object and an error object. Here is an example:

file, err := os.Open("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
The Open function opens the file with the specified name in the current directory. In the example above, we open a file named "example.txt" and assign the returned file object to the file variable. We also use the defer statement to ensure that the file is closed after we are done using it.

Writing to a file

To write data to a file in Go, we can use the WriteString or Write function of the file object. Here is an example:

data := "Hello, World!"
file, err := os.Create("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()

_, err = file.WriteString(data)
if err != nil {
fmt.Println(err)
return
}
In the example above, we create a file named "example.txt", write the string "Hello, World!" to it using the WriteString function, and then close the file using the defer statement.

Reading from a file

To read data from a file in Go, we can use the Read function of the file object. Here is an example:

file, err := os.Open("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()

data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])
In the example above, we open a file named "example.txt", read up to 100 bytes from the file using the Read function, and then print the number of bytes read and the read data.

--

--

No responses yet