To work with files in Go, you can use the os
package which provides functions to create, open, read, write, and manipulate files.
Here's an example of how to read the contents of a file in Go:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// Read from a file
data, err := ioutil.ReadFile("myfile.txt")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println(string(data))
}
In this code, the ioutil.ReadFile()
function is used to read the contents of a file named "myfile.txt" into a byte slice ([]byte
). The function returns the contents of the file as a byte slice and an error if any occurred. You can convert the byte slice to a string using the string()
conversion function for printing.
To write content to a file, you can use the os.OpenFile()
function with the appropriate file open mode:
package main
import (
"os"
)
func main() {
// Open or create a file for writing
file, err := os.OpenFile("myfile.txt", os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Write to the file
_, err = file.WriteString("Hello, World!")
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
}
In this code, the os.OpenFile()
function is used to open or create a file named "myfile.txt" with write-only (os.O_WRONLY
) and create (os.O_CREATE
) modes. The function returns a *File
pointer and an error. Make sure to close the file after you're done with it, which is done using defer file.Close()
.
Then, you can use the WriteString()
method of the file to write content to it. It returns the number of bytes written and an error.
Remember to handle errors appropriately and close the file when you're done to avoid resource leaks.