- Hands-On System Programming with Go
- Alex Guerrieri
- 267字
- 2021-06-24 13:42:27
Writing to file
As we have seen for reading, there are different ways to write files, each one with its own flaws and strengths. In the ioutil package, for instance, we have another function called WriteFile that allows us to execute the whole operation in one line. This includes opening the file, writing its contents, and then closing it.
An example of writing all a file's content at once is shown in the following code:
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Please specify a path and some content")
return
}
// the second argument, the content, needs to be casted to a byte slice
if err := ioutil.WriteFile(os.Args[1], []byte(os.Args[2]), 0644); err != nil {
fmt.Println("Error:", err)
}
}
This example writes all the content at once in a single operation. This requires that we allocate all the content in memory using a byte slice. If the content is too large, memory usage can become a problem for the OS, which could kill the process of our application.
If the size of the content isn't very big and the application is short-lived, it's not a problem if the content gets loaded in memory and written with a single operation. This isn't the best practice for long-lived applications, which are executing reads and writes to many different files. They have to allocate all the content in memory, and that memory will be released by the GC at some point – this operation is not cost-free, which means that is has disadvantages regarding memory usage and performance.