-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflagschallenge01.go
More file actions
56 lines (44 loc) · 1.47 KB
/
flagschallenge01.go
File metadata and controls
56 lines (44 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
/* Alta3 Research | RZFeeser
CHALLEGE 01 - Reading and displaying "n" lines of a file */
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func main() {
var count int
flag.IntVar(&count, "n", 5, "number of lines to read from the file")
flag.Parse()
var in io.Reader
// if flag.Arg(0) is "not" empty, it means there is a trailing arg
// this trailing arg is the name of the file we need to scan
if filename := flag.Arg(0); filename != "" {
f, err := os.Open(filename)
// error handling
if err != nil {
fmt.Println("error opening file: err:", err)
os.Exit(1)
}
defer f.Close() // still close the file if an error occurs
in = f
} else {
// if the user did NOT pass a filename as an argument
// fmt.Println("You forgot to provide data to parse!")
in = os.Stdin // then we read from standard input
}
// read lines from the io.Reader var in
buf := bufio.NewScanner(in)
// iterate up to the value of count user a "for loop"
for i := 0; i < count; i++ {
if !buf.Scan() { // if scanning produces a false
break // because we were asked to scan more lines
} // than actually exist
fmt.Println(buf.Text())
}
if err := buf.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error reading: err:", err)
}
}