Advertisement
Guest User

Untitled

a guest
Nov 1st, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.10 KB | None | 0 0
  1. import (
  2.  "bufio"
  3.    "fmt"
  4.    "io"
  5.    "io/ioutil"
  6.    "os"
  7.    "strconv"
  8. )
  9.  
  10.  
  11. var num = 100
  12.  
  13. // MAIN
  14. func main() {
  15.  
  16.  err := insertStringToFile("test.txt", strconv.Itoa(num))
  17.  if err != nil {
  18.     fmt.Println(err)
  19.     return
  20.  }
  21. }
  22.  
  23. func insertStringToFile(path, str string) error {
  24.  lines, err := File2Lines(path)
  25.  if err != nil {
  26.  return err
  27.  }
  28.  
  29.  fileContent := ""
  30.  for _, line := range lines {
  31.  
  32.  fileContent += str
  33.       fileContent += line
  34.       fileContent += "\n"
  35.  }
  36.  return ioutil.WriteFile(path, []byte(fileContent), 0644)
  37. }
  38.  
  39. func File2Lines(path string) ([]string, error) {
  40.  f, err := os.Open(path)
  41.  if err != nil {
  42.  return nil, err
  43.  }
  44.  // Keep the file open for writing until LinesFromReader is done, then close the channel.
  45.  defer f.Close()
  46.  return LinesFromReader(f)
  47. }
  48.  
  49. func LinesFromReader(r io.Reader) ([]string, error) {
  50.  var lines []string
  51.  scanner := bufio.NewScanner(r)
  52.  for scanner.Scan() {
  53.     num++ // Increment line?
  54.     fmt.Println(num)
  55.     lines = append(lines, scanner.Text())
  56.  }
  57.  if err := scanner.Err(); err != nil {
  58.  return nil, err
  59.  }
  60.  return lines, nil
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement