SoFunction
Updated on 2025-03-05

golang file reading - read according to the specified BUFF size

File content:

ABCDEFGHI

HELLO GOLANG

package main
import (
  "fmt"
  "os"
  "io"
)
func main() {
  fileName := "C:\\Robert\\Log Analysis\\tools_go\\vdn_sqlInterface\\"
  file, err := (fileName, os.O_RDWR, 0666)
  if err != nil {
    ("Open file error!", err)
    return
  }
  defer ()
  stat, err := ()
  if err != nil {
    panic(err)
  }
  var size = ()
  ("file size=", size)
  // define read block size = 2
  buf := make([]byte, 2)
  for {
    length, err := (buf)
    if err != nil {
      if err ==  {
        break
      } else {
        ("Read file error!", err)
        return
      }
    }
    (length, string(buf))
  }
  ("File read ok!")
}

Output:

Read 2 bytes each time and output

file size= 23
2 AB
2 CD
2 EF
2 GH
2 I
2
H
2 EL
2 LO
2 G
2 OL
2 AN
1 GN
File read ok!

Supplement: The address changes before and after golang array append

I won't say much nonsense, let's just read the code~

func main() {
 res := make([]int, 0)
 res = append(res, 1) //The address before and after append in the same function remains unchanged for i, v := range res {
 println(i,v)
 }
}

Print:

0 1

func solve(res []int) {
 res = append(res, 1) //The address before and after append is changed without the same function}
 
func main() {
 res := make([]int, 0)
 for i, v := range res {
 println(i,v)
 }
}

Print:

null

Because append changed the address of the original res. So change it to:

func solve(res []int) []int {
 return append(res, 1)
}
 
func main() {
 res := make([]int, 0)
 for i, v := range solve(res) {
 println(i,v)
 }
}

Print:

0 1

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.