In the actual programming process is unavoidable with the file interaction, through this article to learn to record the Go file operation.

File open and close

Go provides the Open method in the OS package to Open a file. If the operation succeeds, the method of the returned file object can be used to read the data; The corresponding file descriptor has the O_RDONLY mode. If an error occurs, the underlying error type is *PathError.

func Open(name string) (file *File, err error)
Copy the code

We can also Create a new file using the Create method. Truncate the file if it already exists (empty file). If successful, the returned file object can be used for I/O; The corresponding file descriptor has the O_RDWR pattern. If an error occurs, the underlying error type is *PathError.

func Create(name string) (file *File, err error)
Copy the code

There is an open method, and there is a close method. Remember to close the file when we are done with it to free up resources as quickly as possible. Go provides the Close method in OS packages to Close a file so that it cannot be read or written.

func (f *File) Close(a) error
Copy the code

Use the following code to demonstrate the open and close operation of the file.

package main

import "fmt"
import "os"

func main (a) {
    f, err := os.Open("D:\\tmp\\hello.txt")

    iferr ! =nil {
        fmt.Printf("Error opening file, %v", err) / / 1
        return
    }

    fmt.Printf("file: %+v", f) // file: &{file:0xc000112780}
    f.Close()
}
Copy the code

If you open a file that does not exist, code 1 will output “error opening file, open D:\ TMP \hellos. TXT: The system cannot find The file specified.”

For some methods, error will be returned. If it is a necessary operation, it is necessary to determine whether error will be returned in the actual programming process and take corresponding measures.