18.7 文件

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

  1. file, err := os.Open("input.dat")
  2. if err != nil {
  3. fmt.Printf("An error occurred on opening the inputfile\n" +
  4. "Does the file exist?\n" +
  5. "Have you got acces to it?\n")
  6. return
  7. }
  8. defer file.Close()
  9. iReader := bufio.NewReader(file)
  10. for {
  11. str, err := iReader.ReadString('\n')
  12. if err != nil {
  13. return // error or EOF
  14. }
  15. fmt.Printf("The input was: %s", str)
  16. }

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

  1. func cat(f *file.File) {
  2. const NBUF = 512
  3. var buf [NBUF]byte
  4. for {
  5. switch nr, er := f.Read(buf[:]); true {
  6. case nr < 0:
  7. fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
  8. f.String(), er.String())
  9. os.Exit(1)
  10. case nr == 0: // EOF
  11. return
  12. case nr > 0:
  13. if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
  14. fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n",
  15. f.String(), ew.String())
  16. }
  17. }
  18. }
  19. }

链接