Home
Go
os.Open, os.Chmod File Examples
This page was last reviewed on Sep 14, 2022.
Dot Net Perls
Os.Open. In Golang 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.
File
recover
Open, syntax is incorrect. 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.
Cannot file the file. 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.
Tip This error will occur in normal program operation. It is a good reason to test the error return value of 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.
Read file. 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.
And We convert the result to a 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
Unknown escape sequence. Paths in Go must encode the backslash character—we can use double backslashes, or just use tick-syntax for strings.
String Literal
f, err := os.Open("C:\programs\file.txt")
# command-line-arguments C:\programs\file.go:13:27: unknown escape sequence
f, 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.
Tip Calling Close() can avoid "too many files open" errors. It will make programs more reliable.
WaitGroup
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]
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.