Skip to content

Latest commit

 

History

History
65 lines (48 loc) · 962 Bytes

File metadata and controls

65 lines (48 loc) · 962 Bytes

Working with files

Realized by the os package.

Opening a file

filename := "hello.txt"
f, err := os.Open(filename)
if err != nil {
    log.Fatal(err)
}
defer f.Close()

if _, err := io.Copy(os.Stdout, f); err != nil {
    log.Fatal(err)
}

Writing to a file

A file is (implements) io.Writer, but there are convenience methods available in the fmt or io package.

_, _ f.Write([]byte("Hello World"))

Using the fmt package:

fmt.Fprintf(w, "Using Fprintf")
_, _ = io.WriteString(w, "Hello World")

Buffered IO

The bufio package provides methods for buffered reads and writes.

br := bufio.NewReader(os.Stdin)
for {
    line, err := br.ReadString('\n')
    if err == io.EOF {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
}

ioutil package

b, err := ioutil.ReadAll(r)

Exercise

Read a file and print out its size.