Working With Files


Opening and reading a file.

  • os.Open() openx a file for reading
  • ioutil.ReadAll() takes an io.Reader and returns []byte, error
package main

import (
    "fmt"
    "os"
    "io/ioutil"
)

func main() {
    file, err := os.Open("/path/to/file")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    data, err := ioutil.ReadAll(file)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(data))
}

results matching ""

    No results matching ""