golang close file

WBOY
Release: 2023-05-16 10:47:07
Original
577 people have browsed it

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.

The importance of closing files

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) }
Copy after login

Notice that adeferstatement 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.

File closing error

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()
Copy after login

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) } }()
Copy after login

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.

The underlying implementation of os.File.Close()

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.Filetype implements theio.Closerinterface. There is only one method in this interface:

type Closer interface { Close() error }
Copy after login

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() }
Copy after login

Notice that theClose()function also checks some special conditions, for examplefilecan benil, or special standard input output stream. In these cases, the shutdown operation doesn't actually perform any real action.

Close resources by defer

It is a good programming practice to use thedeferkeyword 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() // 读取文件
Copy after login

Since the execution order ofdeferstatements is "last in first out", at any time before the function returns , we can all make sure the file is closed.

Conclusion

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 thedeferkeyword 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!