读文件

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. )
  9. func customRead() {
  10. fileContent, err := os.Open("./shiwo.txt")
  11. if err != nil {
  12. fmt.Println("open file error", err)
  13. }
  14. defer fileContent.Close()
  15. var tmp [128]byte
  16. n, err := fileContent.Read(tmp[:])
  17. fmt.Println(string(tmp[:n]))
  18. }
  19. func BufioRead() {
  20. fileContent, err := os.Open("./shiwo.txt")
  21. if err != nil {
  22. fmt.Println("open file error", err)
  23. }
  24. defer fileContent.Close()
  25. render := bufio.NewReader(fileContent)
  26. for {
  27. //问题:当读到最后时如果最后不存在换行符会导致最后一行无法读取
  28. line, err := render.ReadString('\n')
  29. if err == io.EOF {
  30. return
  31. }
  32. if err != nil {
  33. fmt.Println("render error ", err)
  34. return
  35. }
  36. fmt.Println(line)
  37. }
  38. }
  39. func IoutilRead() {
  40. ret, err := ioutil.ReadFile("./shiwo.txt")
  41. if err != nil {
  42. fmt.Println("read file error", err)
  43. }
  44. fmt.Println(string(ret))
  45. }
  46. func main() {
  47. customRead()
  48. }

写文件

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )
  7. func IoutilWrite() {
  8. err := ioutil.WriteFile("./yy.txt", []byte("niwo"), 0664)
  9. if err != nil {
  10. fmt.Println("writer file failed", err)
  11. }
  12. }
  13. func main() {
  14. //O_RDONLY int = syscall.O_RDONLY // open the file read-only.
  15. //O_WRONLY int = syscall.O_WRONLY // open the file write-only.
  16. //O_RDWR int = syscall.O_RDWR // open the file read-write.
  17. //// The remaining values may be or'ed in to control behavior.
  18. //O_APPEND int = syscall.O_APPEND // append data to the file when writing.
  19. //O_CREATE int = syscall.O_CREAT // create a new file if none exists.
  20. //O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
  21. //O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
  22. //O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
  23. //参数说明,OpenFile(文件名,操作模式,文件权限),文件权限只在linux下生效
  24. file, err := os.OpenFile("./zz.txt", os.O_CREATE|os.O_APPEND, 0644)
  25. if err != nil {
  26. fmt.Println("open file failed", err)
  27. }
  28. file.WriteString("hahaha")
  29. file.Close()
  30. }