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
tempand create the filefile.txtin it.
- Edit the
file.txtfile and writeThis file contentinto the file. - Create the
openfile.gofile 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...