This repository has been archived by the owner on Nov 26, 2018. It is now read-only.
/
fileOperations.go
67 lines (56 loc) · 1.64 KB
/
fileOperations.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
package common
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
)
// AppendString appends a string as a new line in a file
func AppendString(newLine string, fileName string) {
file, openError := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, 0600)
ErrorCheck(openError)
bytesWritten, writeError := file.Write([]byte(newLine + "\n"))
fmt.Println(bytesWritten)
ErrorCheck(writeError)
}
// RemoveString searches a file for a string and removes the line
func RemoveString(lineToRemove string, fileName string) {
inputFromFile, inputError := ioutil.ReadFile(fileName)
ErrorCheck(inputError)
allLines := strings.Split(string(inputFromFile), "\n")
for i, line := range allLines {
if strings.Contains(line, lineToRemove) {
allLines = append(allLines[:i], allLines[i+1:]...)
}
}
outputToFile := strings.Join(allLines, "\n")
writeError := ioutil.WriteFile(fileName, []byte(outputToFile), 0600)
ErrorCheck(writeError)
}
// ReadFirstLine reads in the first line of a file
func ReadFirstLine(fileName string) string {
infile, inError := os.Open(fileName)
ErrorCheck(inError)
defer infile.Close()
scanner := bufio.NewScanner(infile)
scanner.Scan()
text := scanner.Text()
return text
}
// OverwriteFile overwrites a file with content
func OverwriteFile(filename string, content []byte) {
fmt.Println("Test 1")
newFile, createError := os.Create(filename)
fmt.Println("Test 2")
ErrorCheck(createError)
defer newFile.Close()
bytesWritten, writeError := newFile.Write(content)
ErrorCheck(writeError)
fmt.Println(bytesWritten)
}
// DeleteFile ...
func DeleteFile(filePath string) {
removeError := os.Remove(filePath)
ErrorCheck(removeError)
}