From 6268f255cb0d687bfe8aabcd0d188fe33c363faf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Brise=C3=B1o?= Date: Thu, 13 Jan 2022 11:12:24 -0600 Subject: [PATCH 1/2] easy reading and performance --- content/code/go/insert-line-to-file/utils.go | 57 ++++++++------------ 1 file changed, 21 insertions(+), 36 deletions(-) diff --git a/content/code/go/insert-line-to-file/utils.go b/content/code/go/insert-line-to-file/utils.go index 311a3040..8a5e4713 100644 --- a/content/code/go/insert-line-to-file/utils.go +++ b/content/code/go/insert-line-to-file/utils.go @@ -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 + "\n" + lines[index] + + result := strings.Join(lines, "\n") + + return ioutil.WriteFile(path, []byte(result), 0644) } From f42803607a64f607bdae22e7d60ef6564b8c32db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Brise=C3=B1o?= Date: Thu, 13 Jan 2022 13:31:57 -0600 Subject: [PATCH 2/2] no modified line jump --- content/code/go/insert-line-to-file/utils.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/code/go/insert-line-to-file/utils.go b/content/code/go/insert-line-to-file/utils.go index 8a5e4713..694b705b 100644 --- a/content/code/go/insert-line-to-file/utils.go +++ b/content/code/go/insert-line-to-file/utils.go @@ -29,7 +29,7 @@ func InsertStringToFile(path, str string, index int) error { defer f.Close() } - lines[index] = str + "\n" + lines[index] + lines[index] = str + lines[index] result := strings.Join(lines, "\n")