I/O Interactions with "io" and "os" Packages
Learn about the Go stand library’s io and os packages.
We'll cover the following...
os
and io
packages
Let’s start with an example to illustrate what the various functions do.
Press + to interact
package mainimport ("bytes""fmt""io""os")func main() {// create a file to be writtenout, err := os.Create("output/result.txt")if err != nil {panic(err)}defer out.Close()// copy bytes to the previously created filen, _ := io.Copy(out, bytes.NewReader([]byte("simple text to be written")))fmt.Printf("bytes written: %d\n", n)}
This above code creates a new file and writes some content to it. The os.Create
method creates a file at the specified path if one doesn’t exist. If the file already exists, it’ll be truncated. If the file is created, its permission mode is 0666 (read and write).
The io.Copy
method simply copies from a source to a destination until either an EOF
error is encountered or another error occurs.
io
package
The io
package provides us with useful functions and values we can use to manage byte data types. Some values that could be managed are lists of bytes, streams of bytes, or individual bytes. Now, let’s ...