io.go 863 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package util
  2. import (
  3. "io"
  4. )
  5. // A well-behaved substitution for fmt.Fscanln.
  6. // The reader is recommended to be a buffered reader.
  7. // Note that
  8. // 1. trailing \r is ignored
  9. // 2. ...[\n][EOF] and ...[EOF] are not distinguished.
  10. //
  11. func WellBehavedFscanln(f io.Reader) (string, int, error) {
  12. var buf = make([] byte, 0)
  13. var collect = func() string {
  14. var line = DecodeUtf8(buf)
  15. if len(line) > 0 && line[len(line)-1] == '\r' {
  16. line = line[:len(line)-1]
  17. }
  18. return line
  19. }
  20. var total = 0
  21. var one_byte_ [1] byte
  22. var one_byte = one_byte_[:]
  23. for {
  24. var n, err = f.Read(one_byte)
  25. total += n
  26. if err != nil {
  27. if err == io.EOF && len(buf) > 0 {
  28. return collect(), total, nil
  29. } else {
  30. return "", total, err
  31. }
  32. }
  33. if rune(one_byte[0]) != '\n' {
  34. buf = append(buf, one_byte[0])
  35. } else {
  36. return collect(), total, nil
  37. }
  38. }
  39. }