Essential Go edit forum

Working with files and I/O

Go has a very robust support for working with file.

Here's a program that opens a file, reads the whole content and closes the file:

path := "main.go"
f, err := os.Open(path)
if err != nil {
	log.Fatalf("os.Open() failed with '%s'\n", err)
}
defer f.Close()

d, err := ioutil.ReadAll(f)
if err != nil {
	log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

lines := bytes.Split(d, []byte{'\n'})
fmt.Printf("File %s has %d lines\n", path, len(lines))
File main.go has 26 lines

  ↑ ↓ to navigate     ↵ to select     Esc to close