当前位置: 首页 > 文档资料 > Go 入门指南 >

18.7 文件

优质
小牛编辑
125浏览
2023-12-01

(1)如何打开一个文件并读取:

file, err := os.Open("input.dat")
  if err != nil {
    fmt.Printf("An error occurred on opening the inputfilen" +
      "Does the file exist?n" +
      "Have you got acces to it?n")
    return
  }
  defer file.Close()
  iReader := bufio.NewReader(file)
  for {
    str, err := iReader.ReadString('n')
    if err != nil {
      return // error or EOF
    }
    fmt.Printf("The input was: %s", str)
  }

(2)如何通过切片读写文件:

func cat(f *file.File) {
  const NBUF = 512
  var buf [NBUF]byte
  for {
    switch nr, er := f.Read(buf[:]); true {
    case nr < 0:
      fmt.Fprintf(os.Stderr, "cat: error reading from %s: %sn",
        f.String(), er.String())
      os.Exit(1)
    case nr == 0: // EOF
      return
    case nr > 0:
      if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
        fmt.Fprintf(os.Stderr, "cat: error writing from %s: %sn",
          f.String(), ew.String())
      }
    }
  }
}