Hands-On System Programming with Go
上QQ阅读APP看书,第一时间看更新

Summary

In this chapter, we looked at an overview of how to execute file operations in Go. In order to locate files, an extensive array of functions are offered by the filepath package. These can help you execute all kind of operations, from composing paths to extracting elements from it.

We also looked at how to read an operation using various methods, from the easiest and less memory efficient ones that are located in the io/ioutil package to the ones that require an io.Writer implementation to read a fixed chunk of bytes. The importance of the ability to peek content, as implemented in the bufio package, allows for a whole set of operations like read word or read line, which stop the reading operation when a token is found. There are other interfaces that are satisfied by files that are very useful; for example, io.Closer ensures that the resource is released, and io.Seeker is used to move the reading cursor around without the need to actually read the file and discard the output.

Writing a slice of bytes to a file can be achieved in different ways – the io/ioutil package makes it possible to do so with a function call, while for more complex or more memory-efficient operations, there's the io.Writer interface. This makes it possible to write a slice of bytes at a time, and can be used by the fmt package to print formatted data. The buffered writing is used to reduce the amount of actual writing on the disk. This is done with a buffer that collects the content, which then transfers it to a disk every time it gets full. 

Finally, we saw how to accomplish other file operations on the filesystem (creating, deleting, copying/moving, and changing a file's attributes) and took a look at some of the filesystem-related third-party packages, that is, virtual filesystem abstraction and filesystem events notifications.

The next chapter will be about streams, and will focus on all the instances of readers and writers that are not related to the filesystem.