Opening and closing files

When opening a file, there are several options. When calling os.Open(), it just requires a filename and provides a read-only file. Another option is to use os.OpenFile(), which expects more options. You can specify whether you want a read-only or write-only file. You can also choose to read and write, append, create if does not exist, or truncate upon opening. Pass the desired options combined with the logical OR operator. Closing files is done by calling Close() on the file object. You can close a file explicitly or you can defer the call. Refer to Chapter 2, The Go Programming Language for more details on the defer keyword. The following example does not use the defer keyword option, but later examples will:

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.