Working with files
Files are simply sequences of bytes on a storage system. There are two ways of working with files: as a random access byte sequence or as a stream of bytes. We will look at both types of recipes in this section.
Creating and opening files
To work with the contents of a file, you first have to open it or create it. This recipe shows how that can be done.
How to do it...
To open an existing file for reading, use os.Open:
file, err := os.Open(fileName)
if err!=nil {
// handle error
} You can read data from the returned file object, and when you are done, you should close it using file.Close(). So, you can use it as an io.Reader or io.ReadCloser (there are more interfaces that *os.File implements!)
If you attempt to write to the file, you will receive an error from the write operation. On my Linux system, this error is a *fs.PathError message saying bad file descriptor.
To create a new file or to overwrite an existing one, use os.Create:
file...