GoLang操作文件

前端之家收集整理的这篇文章主要介绍了GoLang操作文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

GoLang操作文件方法有很多,这里记录和归纳一下。主要有create/NewFile/Open/OpenFile/Pipe这5个。

  1. func Create(name string) (file *File,err error)
  2. func NewFile(fd uintptr,name string) *File
  3. func Open(name string) (file *File,err error)
  4. func OpenFile(name string,flag int,perm FileMode) (file *File,err error)
  5. func Pipe() (r *File,w *File,err error)

Create方法是默认创建一个权限是0666的空文件,如果文件已经存在就清空它。如果运行成功,就返回一个可以做I/O操作的文件,他的权限是O_RDWR。如果错误,就返回*PathError.

NewFile方法是安装给定的文件描述和名字生成一个文件

Open打开该文件用于读取,如果成功,返回一个用于读取的文件文件权限是O_RDONLY。如果错误,就返回*PathError。

OpenFile是一个广义的调用,大部分的用户使用Create或者Open方法。可以按照指定的flag和perm去打开文件。成功返回一个可用于I/O的文件错误就返回*PathError。

Pipe返回一对连接文件,从r读取,返回bytes写到w。

另外:

  1. const (
  2. O_RDONLY int = syscall.O_RDONLY // open the file read-only.
  3. O_WRONLY int = syscall.O_WRONLY // open the file write-only.
  4. O_RDWR int = syscall.O_RDWR // open the file read-write.
  5. O_APPEND int = syscall.O_APPEND // append data to the file when writing.
  6. O_CREATE int = syscall.O_CREAT // create a new file if none exists.
  7. O_EXCL int = syscall.O_EXCL // used with O_CREATE,file must not exist
  8. O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
  9. O_TRUNC int = syscall.O_TRUNC // if possible,truncate file when opened.
  10. )

  1. //读取文件
  2. package main
  3.  
  4. import(
  5. "os"
  6. "fmt"
  7. "flag"
  8. )
  9.  
  10. func main(){
  11. flag.Parse()
  12. file := flag.Arg(0)
  13. f,err := os.Open(file)
  14. if err != nil{
  15. panic(err)
  16. }
  17. defer f.Close()
  18. buf := make([]byte,100)
  19. for{
  20. rint,_ := f.Read(buf)
  21. if 0==rint{break}
  22. fmt.Println(string(buf[:rint]))
  23. //os.Stdout.Write(buf[:rint])
  24. }
  25. }

  1. //使用bufio读取
  2. package main
  3. import(
  4. "os"
  5. "bufio"
  6. "fmt"
  7. "flag"
  8. )
  9.  
  10. func main(){
  11. flag.Parse()
  12. file := flag.Arg(0)
  13. f,err := os.Open(file)
  14. if err != nil{
  15. panic(err)
  16. }
  17. defer f.Close()
  18. br :=bufio.NewReader(f)
  19. /*
  20. buffer := bytes.NewBuffer(make([]byte,1024))
  21. for{
  22. if part,prefix,err1 := br.ReadLine(); err1!=nil{
  23. break
  24. }
  25. buffer.Write(part)
  26. if !prefix{
  27. lines = append(lines,buffer.String())
  28. buffer.Reset()
  29. }
  30. }
  31. fmt.Println(lines)
  32. */
  33. for {
  34. line,err1:=br.ReadString("\n")
  35. if err == os.EOF{
  36. break
  37. }else{
  38. fmt.Printf("%v",line)
  39. }
  40. }
  41. }
  42.  

猜你在找的Go相关文章