-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathreading-files.go
73 lines (62 loc) · 1.97 KB
/
reading-files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
/*
Reading and writing files are basic tasks needed for many Go programs.
First we’ll look at some examples of reading files.
*/
func checkRead(e error) {
if e != nil {
panic(e)
}
}
// ReadFiles function to illustrate reading files in go.
func ReadFiles() {
// Perhaps the most basic file reading task is
// slurping a file’s entire contents into memory.
dat, err := ioutil.ReadFile("/tmp/dat")
checkRead(err)
fmt.Print(string(dat))
// You’ll often want more control over how and what parts of a file are read.
// For these tasks, start by Opening a file to obtain an os.File value.
f, err := os.Open("/tmp/dat")
defer f.Close()
checkRead(err)
// Read some bytes from the beginning of the file.
// Allow up to 5 to be read but also note how many actually were read.
b1 := make([]byte, 5)
n1, err := f.Read(b1)
checkRead(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1))
// You can also Seek to a known location in the file and Read from there.
o2, err := f.Seek(6, 0)
checkRead(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))
// The io package provides some functions that may be helpful for file reading.
// For example,
// reads like the ones above can be more robustly implemented with ReadAtLeast.
o3, err := f.Seek(6, 0)
checkRead(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
checkRead(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
// There is no built-in rewind, but Seek(0, 0) accomplishes this.
// sets the file position to the beginning of the file of the given stream.
_, err = f.Seek(0, 0)
checkRead(err)
// The bufio package implements a buffered reader that may be useful
// both for its efficiency with many small reads and because of the
// additional reading methods it provides.
r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
checkRead(err)
fmt.Printf("5 bytes: %s\n", string(b4))
}