Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

easy reading and performance #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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)
}