Opening a file by name
File access is a very common operation used to store or read the data. This recipe illustrates how to open a file by its name and path, using the standard library.
How to do it...
- Open the console and create the folder
chapter05/recipe03
. - Navigate to the directory.
- Create the directory
temp
and create the filefile.txt
in it.
- Edit the
file.txt
file and writeThis file content
into the file. - Create the
openfile.go
file with the following content:
package main import ( "fmt" "io" "io/ioutil" "os" ) func main() { f, err := os.Open("temp/file.txt") if err != nil { panic(err) } c, err := ioutil.ReadAll(f) if err != nil { panic(err) } fmt.Printf("### File content ###\n%s\n", string(c)) f.Close() f, err = os.OpenFile("temp/test.txt", os.O_CREATE|os.O_RDWR, os...