Os.Open
In Go a common task is to open a file. We must get a file handle (or descriptor) from the os.Open
func
, part of the "os" package.
Some errors, like "syntax is incorrect" errors or "cannot find file" errors, may be expected. We can test the second result value from os.Open
to see any errors.
Here we pass in a file name that has incorrect syntax. The operating system does not support file names with a question mark in them.
package main import ( "fmt" "os" ) func main() { // This file path is invalid. f, err := os.Open("test?") if err != nil { fmt.Println("Error occurred") fmt.Println(err) return } fmt.Println(f) }Error occurred open test?: The filename, directory name, or volume label syntax is incorrect.
If we call os.Open
and the file is not present on the system, we will also get an error. We can detect this by checking that the error is not nil
.
os.Open
.package main import ( "fmt" "os" ) func main() { // This file does not exist. f, err := os.Open(`C:\perls\vvv`) if err != nil { fmt.Println(err) return } fmt.Println(f) }Error occurred open C:\perls\vvv: The system cannot find the file specified.
We almost always will want to use the file descriptor returned by os.Open
. In this example we pass it to the ioutil.ReadAll
func
.
string
. And then we print the string
to the console.package main import ( "io/ioutil" "fmt" "os" ) func main() { // Open a file. f, err := os.Open(`C:\programs\file.txt`) if err != nil { fmt.Println(err) return } // Pass file descriptor returned by os.Open to ioutil.ReadAll. result, _ := ioutil.ReadAll(f) // Convert byte slice to string. fmt.Println(string(result)) }Thank you Friend
Chmod sets the permissions for a file. In macOS files sometimes cannot be accessed due to lack of Read permissions. By calling Chmod with a special code, we can give it permissions.
package main import ( "fmt" "os" ) func main() { name := "/Users/sam/svg.html" // Set as readable and writable. // Pass 0 to remove all permissions. os.Chmod(name, 0755) // Done. fmt.Println("DONE") }DONE
Paths in Go must encode the backslash character—we can use double
backslashes, or just use tick-syntax for strings.
f, err := os.Open("C:\programs\file.txt")# command-line-arguments C:\programs\file.go:13:27: unknown escape sequencef, err := os.Open(`C:\programs\file.txt`)
Close
It is important to close files that were opened with os.Open
. This can impact programs on macOS that open files on multiple goroutines.
Close()
can avoid "too many files open" errors. It will make programs more reliable.package main import ( "fmt" "os" "io/ioutil" ) func main() { f, _ := os.Open("/Users/sam/timings") data, _ := ioutil.ReadAll(f) // Ensure the file is closed. f.Close() fmt.Println("FILE CLOSED, DATA:", data[0:5]) }FILE CLOSED, DATA: [49 50 47 49 50]
It is important to use both the file object, and the error return value, when calling os.Open
. Many problems will cause an error to be non-nil
.