-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstd_file.go
69 lines (51 loc) · 1.05 KB
/
std_file.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
package main
import (
"bufio"
"errors"
"fmt"
"os"
)
func createNewFile(filePath, content string) error {
// create or replace file
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
// validation
if err != nil {
return errors.New("failed create file")
}
defer f.Close()
f.WriteString(content)
return nil
}
func readFile(filePath string) string {
output := ""
f, err := os.OpenFile("adit.md", os.O_RDONLY, 0666)
defer f.Close()
if err != nil {
return err.Error()
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
output += scanner.Text() + "\n"
}
return output
}
func appendFile(filePath string, content string) error {
// create or replace file
f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0666)
defer f.Close()
if err != nil {
return err
}
if _, err := f.Write([]byte("\n" + content)); err != nil {
return err
}
return nil
}
func main() {
// content := readFile("adit.md")
// fmt.Println(content)
err := appendFile("adit.md", "hello world")
if err != nil {
fmt.Println(err)
}
}