When programming in Golang, we usually need to open, read and write files. However, at the same time, we also need to ensure that we close the file when we are done using it to free up system resources. Therefore, this article will introduce how to close files in Golang.
In Golang, use theos.Open()
function to open the file, useos.Create()
Function can create new files. These functions return instances of type*File
. When we are finished using it, we should use thefile.Close()
function to close the file to release system resources. Otherwise, the file descriptor will leak and eventually the entire system resources will be consumed.
For example, in the following example, we open a file and iterate through all its lines:
file, err := os.Open("example.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) }
Notice that adefer
statement is used here, which will be used in the function Automatically execute thefile.Close()
method before returning. This way ensures that even if an error occurs in the function, the file will be closed correctly.
We can use thefile.Close()
method to close the file. However, sometimes closing a file can go wrong. For example, in the following code, we intentionally open a file that does not exist:
file, err := os.Open("does_not_exist.txt") if err != nil { log.Fatal(err) } defer file.Close()
Since the file does not exist, an error is returned when opening the file. In this case,file.Close()
will trigger another error, causing the close to fail. In this case, we need to make sure we check for errors before closing the file. For example:
file, err := os.Open("does_not_exist.txt") if err != nil { log.Fatal(err) } defer func() { if err := file.Close(); err != nil { log.Fatal(err) } }()
Here, we use an anonymous function and place the file closing operation in this function. While the function is executing, we again check if an error occurred while closing the file. If the shutdown fails, we can call thelog.Fatal()
function to log the error and exit the program.
In the underlying implementation, closing the file is just an operating system call, calling theclose()
system function to close the file Descriptor. In Golang, theos.File
type implements theio.Closer
interface. There is only one method in this interface:
type Closer interface { Close() error }
inos.File
, theClose()
function actually simply calls thesyscall.Close()
function.
func (file *File) Close() error { if file == nil { return syscall.EINVAL } if file == os.Stdin || file == os.Stdout || file == os.Stderr { return nil } return file.file.close() }
Notice that theClose()
function also checks some special conditions, for examplefile
can benil
, or special standard input output stream. In these cases, the shutdown operation doesn't actually perform any real action.
It is a good programming practice to use thedefer
keyword when opening a file. This way, we can ensure that the file is closed even if an error occurs before the function returns. For example, the following code will automatically close the file after reading it:
file, err := os.Open("example.txt") if err != nil { log.Fatal(err) } defer file.Close() // 读取文件
Since the execution order ofdefer
statements is "last in first out", at any time before the function returns , we can all make sure the file is closed.
In Golang, use theos.Open()
function to open the file, and use thefile.Close()
method to close the file to release resources. We should make sure to check for errors and log them when closing the file. Additionally, using thedefer
keyword ensures that when a file is used and manipulated, it is always closed properly.
The above is the detailed content of golang close file. For more information, please follow other related articles on the PHP Chinese website!