Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 21 additions & 36 deletions content/code/go/insert-line-to-file/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,36 @@ package insert

import (
"bufio"
"io"
"io/ioutil"
"log"
"os"
"strings"
)

func File2lines(filePath string) ([]string, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
return LinesFromReader(f)
}

func LinesFromReader(r io.Reader) ([]string, error) {
func InsertStringToFile(path, str string, index int) error {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
{
f, err := os.Open(path)
if err != nil {
log.Print(err)
}

return lines, nil
}
scanner := bufio.NewScanner(f)

/**
* Insert sting to n-th line of file.
* If you want to insert a line, append newline '\n' to the end of the string.
*/
func InsertStringToFile(path, str string, index int) error {
lines, err := File2lines(path)
if err != nil {
return err
}
for scanner.Scan() {
lines = append(lines, scanner.Text())
}

fileContent := ""
for i, line := range lines {
if i == index {
fileContent += str
if err := scanner.Err(); err != nil {
log.Print(err)
}
fileContent += line
fileContent += "\n"

defer f.Close()
}

return ioutil.WriteFile(path, []byte(fileContent), 0644)
lines[index] = str + lines[index]

result := strings.Join(lines, "\n")

return ioutil.WriteFile(path, []byte(result), 0644)
}