-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
76 lines (67 loc) · 1.47 KB
/
main.go
File metadata and controls
76 lines (67 loc) · 1.47 KB
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
74
75
76
// head - display first lines of a file.
package main
import (
"solod.dev/so/bufio"
"solod.dev/so/flag"
"solod.dev/so/fmt"
"solod.dev/so/io"
"solod.dev/so/mem"
"solod.dev/so/os"
)
var nLines int
var nBytes int
func main() {
parseFlags()
args := flag.Args()
if len(args) == 0 {
head(os.Stdin)
os.Exit(0)
}
exitCode := 0
for i, fname := range args {
if len(args) > 1 {
if i > 0 {
fmt.Println("")
}
fmt.Println("==>", fname, "<==")
}
f, err := os.Open(fname)
if err != nil {
fmt.Printf("head: %s: No such file or directory\n", fname)
exitCode = 1
continue
}
head(&f)
f.Close()
}
os.Exit(exitCode)
}
// parseFlags parses command-line flags.
func parseFlags() {
flag.IntVar(&nLines, "n", 10, "print count lines of each of the specified files")
flag.IntVar(&nBytes, "c", 0, "print bytes of each of the specified files")
flag.Parse()
}
// head writes the first nLines lines or nBytes bytes
// from r to standard output.
func head(r io.Reader) {
if nBytes > 0 {
headBytes(r, nBytes)
} else {
headLines(r, nLines)
}
}
// headLines writes the first count lines from r to standard output.
func headLines(r io.Reader, count int) {
scanner := bufio.NewScanner(mem.System, r)
defer scanner.Free()
printed := 0
for printed < count && scanner.Scan() {
fmt.Println(scanner.Text())
printed++
}
}
// headBytes writes the first count bytes from r to standard output.
func headBytes(r io.Reader, count int) {
io.CopyN(os.Stdout, r, int64(count))
}