os.Open
The Go function that opens a file for reading and returns an *os.File you can stream from and must close.
In more detail
Check the error, then write defer f.Close() on the next line so the file is closed on every path. An *os.File is an io.Reader, so it works with io.Copy and other stream helpers. os.Create is the matching call for writing.
Example
f, err := os.Open("app.log")
if err != nil { ... }
defer f.Close()Related terms
- defer — A Go statement that schedules a function call to run when the surrounding function returns, used for cleanup such as closing a file.
- io.Reader — The Go interface for anything you can read bytes from, such as a file, a network connection or an HTTP response body.
- file descriptor — A small number the operating system gives a process for each open file, socket or pipe, used in every later read or write.
- os.ReadFile — The Go function that reads a whole file into memory in one call and returns its bytes and an error.
Taught in
- Files and the os Package — Concurrent Systems Programming with Go