-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
49 lines (46 loc) · 1.06 KB
/
main.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
package main
import (
"fmt"
"bufio"
"os"
)
const fileName = "typeInfo.txt"
func main() {
file, size := openExistingFile()
defer file.Close()
if size > 0 {
writeToFile(file, os.Stdin)
} else {
var name string
fmt.Print("Please enter your name: ")
fmt.Scanf("%s", &name)
fmt.Printf("Hello %s \xF0\x9F\x98\x83 \n", name)
newFile, err := os.Create(fileName)
newFile.WriteString(name + " is writing this file \n")
if err != nil {
fmt.Print("Unable to create the file")
}
writeToFile(*newFile, os.Stdin)
}
}
func openExistingFile() (os.File, int64) {
fmt.Println("Please type in the terminal \xF0\x9F\x98\x83 \n")
fileName := fileName
file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return os.File{}, 0
}
fInfo, err := file.Stat()
size := fInfo.Size()
return *file, size
}
func writeToFile(file os.File, input *os.File) {
s := bufio.NewScanner(input)
for s.Scan() {
if err := s.Err(); err != nil {
fmt.Fprint(os.Stderr, "Reading error from input", err)
} else {
file.WriteString(s.Text() + "\n")
}
}
}