Before we can begin using files for our programs, we need to, first, understand the basics of how files work in Go.
Consider the following file tree. We will be using this file tree to aid in our understanding of files in Go. This tree contains .txt files, as well as, special directories, testdata, _ignore, and .hidden. We will cover the importance of these files, and directories, as we progress.
Reading a Directory
In order to know which files we can work with, we need to know which files are in a directory. To do this we can use the os.ReadDir function, Listing 14.2.
The os.ReadDir function takes a path as a parameter, and returns a slice of os.DirEntry values, Listing 14.3. Each os.DirEntry value represents a file or directory in the directory, and contains information about the file or directory.
In go1.16 the fs package was added, which provides interface around the file system. The result of this was that many types were aliased to the fs package. This means that you may need to hunt a little further to find the deeper documentation.
We can use the os.ReadDir function to read the contents of the data directory. We then print the names to the console. If the file is a directory, we prepend it with a ->.
As we can see from the output of the program, only the files in the data directory are listed. The os.ReadDir function will only read the contents of the directory, and not the contents of any subdirectories. To get a full list of files, including the contents of subdirectories, we will need to walk the directories ourselves. We will discuss this more later.
The FileInfo Interface
The main source for metadata about files is the fs.FileInfo interface, Listing 14.7. In go1.16 the os.FileInfo type was aliased to fs.FileInfo. From this interface we can get the name of the file, the size of the file, the time the file was last modified, and the mode, or permissions, of the file. We can also tell if the file is a directory, or a regular file.
Consider Listing 14.8. We read the contents of the data directory, and print the mode, size, and name of each file.