-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappendlines.go
More file actions
46 lines (38 loc) · 861 Bytes
/
appendlines.go
File metadata and controls
46 lines (38 loc) · 861 Bytes
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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func main() {
//make sure filename is given on command line
if len(os.Args) < 2 {
log.Fatalf("Usage: %s <filename>", os.Args[0])
}
// Get the filename from the cmd line
filename := os.Args[1]
// Open the file
file, err := os.Open(filename)
if err != nil {
log.Fatalf("Failed to open file: %s", err)
}
defer file.Close()
//screate a new scanner for the file
scanner := bufio.NewScanner(file)
//slice to hold each line
var lines []string
//Read each line
for scanner.Scan() {
//fmt.Println(scanner.Text())
lines = append(lines, scanner.Text())
}
// Check for errors reading the line
if err := scanner.Err(); err != nil {
log.Fatalf("error reading from file: %s", err)
}
// join the lines with a comma
result := strings.Join(lines, ",")
fmt.Println(result)
}