Standard library / os
os.Open()
Opens a file for reading; handle the error before using the returned handle and close it afterward. Example uses a disposable temporary workspace. Expected stdout: 'abc\n'.
Formal Syntax & Structure
go syntaxgo
func Open(name string) (*File, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | Name or pathname of the target. |
Return Value
(*File, error)
Opens a file for reading; handle the error before using the returned handle and close it afterward.
Working Example
Example Snippetgo
package main
import ( "fmt" "io" "os")
func check(e error) { if e != nil { panic(e) }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() { root, e := os.MkdirTemp("", "bytemind-go-") check(e) old, e := os.Getwd() check(e) check(os.Chdir(root)) return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() { defer workspace()() seed() f, e := os.Open("a.txt") check(e) defer f.Close() b, e := io.ReadAll(f) check(e) fmt.Println(string(b))}