To work with files, we can use the functionality of the OS package. All files in Go are represented by the os.File
type.
This type implements several interfaces, such as `io.Reader
` and `io.Writer
`, which allows you to read the contents of a file and write the data to a file.
Using the os.Create()
function , you can create a file at a specific path. The path to the file is passed as a parameter. If a similar file already exists, it is overwritten:
file, err := os.Create("test.txt")
The function returns an os.File
object for working with the file and information about the error that may occur when creating the file.
The previously created file can be opened using the os.Open()
function:
file, err := os.Open("test.txt")
This function also returns an os.File
object for working with the file and information about the error that might occur when opening the file.
We also have at our disposal the os.OpenFile()
function, which opens a file, and if the file does not exist, then creates it. It takes three parameters:
- the path to the file
- file opening mode (for reading, for writing, etc.)
- file permissions
For example:
// Open a file for Reading
file1, err := os.OpenFile("testfilw.txt", os.O_RDONLY, 0666)
// Open a file for Writing
file2, err := os.OpenFile("test.txt", os.O_WRONLY, 0666)
After finishing working with the file, you should close it using the Close()
method.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("testFile.txt") // Create a file
if err != nil{ // Check for an error
fmt.Println("Unable to create file:", err)
os.Exit(1) // exit the program
}
defer file.Close() // Close the file
fmt.Println(file.Name()) // Print the file name
}
Using the os.Exit()
function you can exit the program. The method Name()
defined for the os.File
type allows you to get the file name.